0

I would like to parse JSON string with nested array to POJO with Gson but it seems that it does not work.

My JSON string is as follow:

{
   "magdeburg":{
      "average":"21.40",
      "maximum":"22.33",
      "minimum":"19.06"
   },
   "frankfurt":{
      "average":"16.41",
      "maximum":"16.57",
      "minimum":"16.09"
   }
}

with my POJO class as follow:

public class PingResult {

    public double average;
    public double maximum;
    public double minimum;

    public PingResult(double average, double maximum, double minimum) {
        this.average= average;
        this.maximum =  maximum;
        this.minimum= minimum;
    }

    public String toString() {
        return "average:" + this.average + ",maximum:"+this.maximum+",minimum:"+this.minimum;
    }
}

but when I want to parse it to POJO with the code like this:

List<PingResult> pr =  (List<PingResult>) gson.fromJson(q, PingResult.class);
        for(PingResult p:pr) {
            System.out.println(p.toString());
        }

it gave error of

java.lang.ClassCastException: PingResult cannot be cast to java.util.List at DelayBasedMeasurement.main(DelayBasedMeasurement.java:380).

I have tried to parse to PingResult[] but still it does not work.

Any advice?

2 Answers 2

1

Not sure how to do it with a List, but this is how to do it with Map:

Map<String, Ping> map = gson.fromJson(json, new TypeToken<Map<String, Ping>>(){}.getType());

Then you can just map.values() if you want all the values.

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

Comments

1

First, gson.fromJson(q, PingResult.class) won't return a List, only a single object. You need to use a TypeToken.

Secondly, you don't have a list of JSON objects, you have a map. There are no [] characters, and each ping result is the value of the city string key.

Try TreeMap<String, PingResult> as your deserialization type

Type pingType =  new TypeToken<TreeMap<String, PingResult>>(){}.getType();

TreeMap<String, PingResult> pingMap = gson.fromJson(json, pingType);

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.