[英]Converting JSON string to Java Object: Java
我有一个弦
String aString = "[{code:32022,estCode:0,timeZone:CE},{code:59400,estCode:0,timeZone:CE},{code:59377,estCode:0,timeZone:CE},{code:59525,estCode:0,timeZone:CE},{code:59560,estCode:0,timeZone:CE}]"
我正在尝试使用gson将此字符串转换为Map[]
。
我尝试使用
Gson gsn = new GsonBuilder().create();
Map[] b = gsn.fromJson(aString , Map[].class);
我能够正确解析它,并得到输出
[{code=32022.0, estCode=0.0, timeZone=CE}, {code=59400.0, estCode=0.0, timeZone=CE}, {code=59377.0, estCode=0.0, timeZone=CE}, {code=59525.0, estCode=0.0, timeZone=CE}, {code=59560.0, estCode=0.0, timeZone=CE}]
但值转换为双倍,我需要它作为字符串。 例如:32022转换为32022.0我需要它,因为32022有什么办法可以使用gson中的ExclusionStrategy
做到这一点。 我在ExclusionStrategy, shouldSkipClass and shouldSkipField
仅看到两种方法ExclusionStrategy, shouldSkipClass and shouldSkipField
还有其他使用gson的方法。
请帮忙
无法更改值的类型,但是您可以使用自己的类,如下所示:
public static void main(String[] args) {
String aString = "[{code:32022,estCode:0,timeZone:CE},{code:59400,estCode:0,timeZone:CE},{code:59377,estCode:0,timeZone:CE},{code:59525,estCode:0,timeZone:CE},{code:59560,estCode:0,timeZone:CE}]";
Gson gsn = new GsonBuilder().create();
TimeCode[] b = gsn.fromJson(aString, TimeCode[].class);
for(TimeCode entry:b){
System.out.print(entry+",");
}
}
class TimeCode{
String code;
String estCode;
String timeZone;
public String toString(){
return "code="+code+",estCode="+estCode+",timeZone="+timeZone;
}
}
输出:
code=32022,estCode=0,timeZone=CE,code=59400,estCode=0,timeZone=CE,code=59377,estCode=0,timeZone=CE,code=59525,estCode=0,timeZone=CE,code=59560,estCode=0,timeZone=CE,
希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.