GSON : java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY

StackOverflow https://stackoverflow.com/questions/23275261

  •  09-07-2023
  •  | 
  •  

Domanda

I am trying to parse the below json string using gson and I am getting this exception mentioned.

[{"target":"target 1","datapoints":[[12345678, null],[3456123,null],[908976712,12345677.0],[67543678, 4567.0]]}, {"target":"target 2","datapoints":[[12345678, 50215.0],[345645123,null],[908976712,null],[67543678, 4567.0]]}]

Here is my model class: Metric

public class Metric implements Serializable{
String target;
Datapoint[] datapoints;

//setters and getters
}

Datapoint

public class Datapoint implements Serializable{
long time;
long count;
//setters and getters
}

This is how I am trying to parse the json using gson

Gson gson = new GsonBuilder().create();
 JsonArray array = jsonParser.parse(jsonString).getAsJsonArray();
 for (JsonElement element : array) {
      Metric metric = gson.fromJson(element, Metric.class);
      //do something with the metric object. probably read all the datapoints and display
 }

This is the exception thrown

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY

The exception is clear that its expecting an object (probably the Datapoint), but it encountered an array. I am sure that my model class is the one causing the issue, but I dont understand what should my model class look like for that json to be parsed without failing.

È stato utile?

Soluzione

Your datapoints elements are not JSON objects, they are JSON arrays, seemingly made up of JSON numbers and JSON nulls.

[
    12345678,
    null
],

You won't be able (by default) to map that to a Datapoint POJO. You can instead have a

Integer[][] datapoints; 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top