Skip to content Skip to sidebar Skip to footer

Gson Deserialization - Trying To Parse A Json To An Object

I am trying to parse a JSON into an Object. There are two classes: User and Profile. User got an instance of Profile. So now there is one JSON to build an User Object. Inside this

Solution 1:

Use a Gson Deserializer class. they are pretty straightforward:

To make this work, you have to make sure the parser isn't going to try and serialize the infringing object (in this case your Map). I would rename your map object to _links or somesuch so the serializer will skip over it. Do the same thing as this example for your Profile as well.

Once you've done that you have to deserialize it and make sure to include the deserializer in the gson object:

    User u;
    GsonBuildergb=newGsonBuilder();
    gb.registerTypeAdapter(User.class, newUserDeserializer());
    Gsong= gb.create();
    u = g.fromJson(json, User.class);


publicclassUserDeserializerimplementsJsonDeserializer<UserDeserializer>
{
   @Overridepublic User deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
    {
        Useru= g.fromJson(json, User.class);
        JsonObjectjo= (JsonObject)json;
        JsonElementje= jo.get("links");
        //iterate through the je element to fill your map.
    }

}

Post a Comment for "Gson Deserialization - Trying To Parse A Json To An Object"