1

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

7
  • Possible duplicate of Gson. Deserialize integers as integers and not as doubles Commented 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. Commented Jan 8, 2016 at 11:19
  • @NikhiK.Bansal It is Map[] Commented Jan 8, 2016 at 11:20
  • @MichaelDibbets Is there any way to do it using gson Commented 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.? Commented Jan 8, 2016 at 11:37

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.