我使用的net.sf.json是json-lib-2.4-jdk15.jar,把json对象转换为普通java实体对象时候有个问题,josn对象转换为java对象之后,json串里面的那几个小数点的值对应的java属性的值取不到。
json串如下所示:
{"Average":0.28,"Maximum":0.32,"Minimum":0.2,"instanceId":"i-426auf2hf","timestamp":1449938400000,"userId":"1467232540347717"}
java实体对象如下:
public class Model {
private double Average;
private double Maximum;
private double Minimum;
private String instanceId;
private long timestamp;
private String userId;
public double getAverage() {
return Average;
}
public void setAverage(double average) {
Average = average;
}
public double getMaximum() {
return Maximum;
}
public void setMaximum(double maximum) {
Maximum = maximum;
}
public double getMinimum() {
return Minimum;
}
public void setMinimum(double minimum) {
Minimum = minimum;
}
public String getInstanceId() {
return instanceId;
}
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
}
转换代码如下:
JSONObject sfObject = JSONObject.fromObject(str);
// 转换方法
Model ecs = (Model) JSONObject.toBean(sfObject, Model.class);
System.out.println(ecs.getAverage());
Average的值拿不到,所以输出的结果是:0.0,而不是0.28。
解决方案:
我放弃了json.lib,用google的Gson能够完美的解决。
Gson把json串转换成java实体对象的方法如下:
1.首页导入Gson的jar包,网上可以下载。
2. 实体类还是使用上面的实体类,转换代码如下所示:
String str = "{\"Average\":0.29,\"Maximum\":0.32,\"Minimum\":0.25,\"instanceId\":\"i-426auf2hf\",\"timestamp\":1449939900000,\"userId\":\"1467232540347717\"}";
Model model = new Gson().fromJson(str, Model.class);
System.out.println(model.getAverage());
使用Gson之后,打印结果正确。 |