我有一个字符串
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 ,我需要它作为字符串。
例如:32022 转换为 32022.0 我需要它,因为 32022 有什么方法可以在 gson 中使用 ExclusionStrategy
来实现。我在 ExclusionStrategy、shouldSkipClass 和 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,
希望对您有所帮助。
关于java - 将 JSON 字符串转换为 Java 对象 : Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34675671/