我正在尝试将 JSON 字符串转换为 POJO 和从 POJO 转换。我想知道对于不同类型的 json 是否最好有一个新的类定义。正如我认为让 google gson 必须解析空字段会减慢它的速度。(不是很明显,但仍然。我认为值得进行实验并在此处发布。)例如登录客户端可能是。
public class CustomJSON {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
但我可以从客户那里收到其他东西,例如。最喜欢的颜色,食物等。
public class CommonJSON {
private String name;
private String food;
private String music;
//getters and setters.
}
所以我进行了测试。
CustomJson 与上面相同,并且使用 CommonJSON 我添加了 50 个其他空字段,这些字段将不使用 a 到 ax。
public class CommonJSON {
private String name;
private String a;
...
private String ax;
//getters and setters.
}
我运行测试的主要方法如下。
public static void main(String[] args) {
// TODO Auto-generated method stub
String theJSON = "";
int passes = 100;
long start;
long finish;
long exeTime;
Gson gson = new Gson();
//custom JSON
start = System.nanoTime();
for(int i=0;i<passes;i++)
{
CustomJSON custom = new CustomJSON();
custom.setName("StackOverFlow");
theJSON = gson.toJson(custom);
}
finish = System.nanoTime();
System.out.println(theJSON);
exeTime = finish-start;
System.out.println("Custom JSON \n\t>\t "+(exeTime)+" Nano seconds");
System.out.println(" \t>\t "+Math.round((exeTime)/1000000.0)+" Micro seconds\n");
//common JSON
start= System.nanoTime();
for(int i=0;i<passes;i++)
{
CommonJSON toClientJSONd = new CommonJSON();
toClientJSONd.setName("StackOverFlow");
theJSON = gson.toJson(toClientJSONd);
}
finish = System.nanoTime();
System.out.println(theJSON);
exeTime = finish-start;
System.out.println("Common JSON \n\t>\t "+(exeTime)+" Nano seconds");
System.out.println(" \t>\t "+Math.round((exeTime)/1000000.0)+" Micro seconds");
}
The results are not as I expected. With 100 passes the common class finishes 10ms faster on my machine. If I increase the number of passes the common class eventually starts to lag behind.
What makes the common class faster to start of with? Should I worry about this in my code or just use one class for a common class for all jsons?
I can provide full source and an eclipse project if anyone would like to run it.