我有一个字符串
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}]
但是值被转换为double我需要它作为String。
例如:32022被转换为32022.0我需要它,因为32022有任何方法可以使用gson中的ExclusionStrategy
。我发现在ExclusionStrategy, shouldSkipClass and shouldSkipField
中只有两种方法可以使用gson进行其他方法。
请帮忙
答案 0 :(得分:1)
无法更改值的类型,但您可以使用自己的类,如下所示:
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,
我希望它有所帮助。