I have a String
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}]"
I am trying to convert this string to Map[] using gson.
I tried using
Gson gsn = new GsonBuilder().create();
Map[] b = gsn.fromJson(aString , Map[].class);
I am able to parse it properly and I am getting output as
[{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}]
but the values are converted to double i need it as String.
Ex: 32022 is converted to 32022.0 i need it as 32022 is there any way i can do it using ExclusionStrategy in gson. I am seeing only two methos availalbe in ExclusionStrategy, shouldSkipClass and shouldSkipField is there any other way to do it using gson.
Please help
-
Possible duplicate of Gson. Deserialize integers as integers and not as doublesTschallacka– Tschallacka2016年01月08日 11:13:47 +00:00Commented Jan 8, 2016 at 11:13
-
map follow key value but you have 3 attribute in your json element {code:32022,estCode:0,timeZone:CE}, what kind of map you want.Nikhi K. Bansal– Nikhi K. Bansal2016年01月08日 11:19:15 +00:00Commented Jan 8, 2016 at 11:19
-
@NikhiK.Bansal It is Map[]anonymous– anonymous2016年01月08日 11:20:21 +00:00Commented Jan 8, 2016 at 11:20
-
@MichaelDibbets Is there any way to do it using gsonanonymous– anonymous2016年01月08日 11:24:50 +00:00Commented Jan 8, 2016 at 11:24
-
What is type of "code" field in Map object String or double? Can you provide code of Map Object.?Kishan Vaghela– Kishan Vaghela2016年01月08日 11:37:28 +00:00Commented Jan 8, 2016 at 11:37
1 Answer 1
There is no way to change the type of the values, but you could use an own class for that like this:
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;
}
}
Output:
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,
I hope it helps.