Gson deserialization - Trying to parse a JSON to an Object

前端 未结 1 1997
南笙
南笙 2020-12-21 06:45

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 Objec

相关标签:
1条回答
  • 2020-12-21 07:31

    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;
        GsonBuilder gb = new GsonBuilder();
        gb.registerTypeAdapter(User.class, new UserDeserializer());
        Gson g = gb.create();
        u = g.fromJson(json, User.class);
    
    
    public class UserDeserializer  implements JsonDeserializer<UserDeserializer>
    {
       @Override
       public User deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        {
            User u = g.fromJson(json, User.class);
            JsonObject jo = (JsonObject)json;
            JsonElement je = jo.get("links");
            //iterate through the je element to fill your map.
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题