Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON String to Java object using GSON

Tags:

I am trying to parse json to java.

I have the following string that is valid json according to jsonlint.com

private final static String LOC_JSON =           "["         +"{"         +"  \"lat1\": 39.737567,"         +"  \"lat2\": 32.7801399,"         +"  \"long1\": -104.98471790000002,"         +"  \"long2\": -96.80045109999998"         +"},"         +"  ["         +"      {"         +"          \"lat\": {"         +"              \"b\": 38.88368709500021,"         +"              \"d\": 40.620468491667026"         +"          },"         +"          \"long\": {"         +"          \"b\": -105.75306170749764,"         +"          \"d\": -104.675854661387"         +"          }"         +"      }"         +"  ]"         +"]"; 

I am trying to parse it into an object and I get the following error. "Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2"

            Gson gson = new Gson();         BoxSearch b = gson.fromJson( LOC_JSON, BoxSearch.class );  

BoxSearch consists of this.

private Number lat1; private Number lat2; private Number long1; private Number long2; private Boxes[] boxes; 

Boxes is a Latitude object and a Longitude object which are both defined identical.

private String b; private String d; 

I can parse the higher level attributes (lat1,lat2,long1 and long2) into a more simple BoxSearch object that only has those 4 attributes. The trouble comes when the json and the object are more complex. Is it even possible to do what I am trying?

I hope I have provided enough information to get some help. I would be happy to provide more info or even a test project if need be. I am running this as a junit test.

Thanks.

like image 217
user2415153 Avatar asked May 23 '13 20:05

user2415153


People also ask

How do you convert JSON to Java object?

We can convert a JSON to Java Object using the readValue() method of ObjectMapper class, this method deserializes a JSON content from given JSON content String.

Can we convert string to object in Java?

We can also convert the string to an object using the Class. forName() method. Parameter: This method accepts the parameter className which is the Class for which its instance is required.

How do I deserialize JSON with Gson?

Deserialization – Read JSON using Gson. Deserialization in the context of Gson means converting a JSON string to an equivalent Java object. In order to do the deserialization, we need a Gson object and call the function fromJson() and pass two parameters i.e. JSON string and expected java type after parsing is finished ...


2 Answers

Gson gson = new Gson(); gson.fromJson(jsonStr,YourClass.class); 

very easy.

like image 111
David Wang Avatar answered Sep 20 '22 11:09

David Wang


The reason for the error is that your JSON at the top level is an array, not an object. That is covered by GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"?.

However, the solution there won't work for your JSON because you have an array of mixed types (an object and an array) rather than an array of a single type of object. For that you're going to have to write a custom deserializer (See The section of the Gson user's guide that covers this) or use Gson's JsonParser class directly and extract the data from the parse tree.

Edit from comments above:

If you're the one creating the JSON, it looks like what you want is an array of BoxSearch objects?

Based on your Java BoxSearch class, you'd need JSON structured like:

[     {         "lat1" : 39.737567,         "lat2" : 32.7801399,         "long1" : -104.98471790000002,         "long2" : -96.80045109999998,         "boxes" : [                      {                       "lat": {                           "b": 38.88368709500021,                           "d": 40.620468491667026                       },                       "long": {                           "b": -105.75306170749764,                           "d": -104.675854661387                       }                     }                   ]     } ] 

However, the way you have Boxes class defined won't work for that. (Did you mean to have an array of them?). As-is it would need to look like:

class Boxes {     Box lat;     @SerializedName("long")     Box lon; }  class Box {    String b;    String d; } 

Now you have an array containing one type of object (BoxSearch) which you could deserialize with:

Type collectionType = new TypeToken<Collection<BoxSearch>>(){}.getType(); Collection<BoxSearch> boxSearchCollection = gson.fromJson(json, collectionType); 

If you really don't need an array of these, get rid of the outer array and simply do:

gson.fromJson(json, BoxSearch.class); 
like image 41
Brian Roach Avatar answered Sep 18 '22 11:09

Brian Roach