JSON String to Java object using GSON

54,454

Solution 1

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);

Solution 2

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

very easy.

Share:
54,454
user2415153
Author by

user2415153

Updated on December 18, 2020

Comments

  • user2415153
    user2415153 over 3 years

    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.

  • user2415153
    user2415153 almost 11 years
    Thank you very much Brian, that slight tweak to the json and all is well. I would vote this answer up but I have no "street cred". The code works like a champ. In case people copy and paste this answer, Box long; needs to be renamed :-)
  • user2415153
    user2415153 almost 11 years
    Oh and yes I needed the array. Thanks again.
  • Brian Roach
    Brian Roach almost 11 years
    @user2415153 I changed the code so it'll work with "long" in the JSON - see the answer now :) I didn't notice that, sorry. As for upvoting - you can accept my answer ;) and glad I could help!
  • user2415153
    user2415153 almost 11 years
    Fancy solution! I just renamed the variables to the full words. Accepting as answered! Thanks again!
  • Ashkan
    Ashkan over 7 years
    it help me to convert a json object that have a list inside. I convert the json string to Object.class