最近要测试两款json解析器的性能, 需要生成不同结构的json, 上网看了下貌似没有, 就花半天撸了一个, 写个文章记录下.
代码在https://github.com/Mazexal/buildJson
核心代码:
private static String buildObjectBase(int length,int depthlevel){
StringBuilder stringBuilder=new StringBuilder();
stringBuilder.append("{");
for(int i=0;i<length;i++){
int num = getRandInt(5,20);
stringBuilder.append("\"");
stringBuilder.append(strBuild(num));
stringBuilder.append("\"");
num=getRandInt(5,20);
stringBuilder.append(":");
int choose=getRandInt(4,4);
int tmp = getRandInt(3,4);
if(depthlevel>5){
choose=5;
}
switch (choose){
case 0:
depthlevel =depthlevel+1;
stringBuilder.append(buildObjectBase(tmp,depthlevel+1));
break;
case 1:
depthlevel =depthlevel+1;
stringBuilder.append(buildArray(tmp,depthlevel+1));
break;
default:
stringBuilder.append("\"");
stringBuilder.append(strBuild(num));
stringBuilder.append("\"");
break;
}
if(i!=length-1){
stringBuilder.append(",");
}
}
stringBuilder.append("}");
return (stringBuilder.toString());
}
private static String buildArray( int depth,int depthlevel){
StringBuilder stringBuilder=new StringBuilder();
stringBuilder.append("[");
for(int i=0;i<depth;i++){
int length = getRandInt(5,12);
stringBuilder.append(buildObjectBase(length,depthlevel+1));
if(i!=depth-1){
stringBuilder.append(",");
}
}
stringBuilder.append("]");
// stringBuilder.append(",");
return stringBuilder.toString();
}
采用递归调用, 可以自由生成不同的结构.