How can I convert JSON to a HashMap using Gson?

前端 未结 16 2354
臣服心动
臣服心动 2020-11-22 05:14

I\'m requesting data from a server which returns data in the JSON format. Casting a HashMap into JSON when making the request wasn\'t hard at all but the other way seems to

16条回答
  •  名媛妹妹
    2020-11-22 05:49

    I have overcome a similar problem with a Custom JsonDeSerializer. I tried to make it a bit generic but still not enough. It is a solution though that fits my needs.

    First of all you need to implement a new JsonDeserializer for Map objects.

    public class MapDeserializer implements JsonDeserializer>
    

    And the deserialize method will look similar to this:

    public Map deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
    
            if (!json.isJsonObject()) {
                return null;
            }
    
            JsonObject jsonObject = json.getAsJsonObject();
            Set> jsonEntrySet = jsonObject.entrySet();
            Map deserializedMap = new HashMap();
    
            for (Entry entry : jsonEntrySet) {
                try {
                    U value = context.deserialize(entry.getValue(), getMyType());
                    deserializedMap.put((T) entry.getKey(), value);
                } catch (Exception ex) {
                    logger.info("Could not deserialize map.", ex);
                }
            }
    
            return deserializedMap;
        }
    

    The con with this solution, is that my Map's key is always of Type "String". However by chaning some things someone can make it generic. In addition, i need to say, that the value's class should be passed in the constructor. So the method getMyType() in my code returns the type of the Map's values, which was passed in the constructor.

    You can reference this post How do I write a custom JSON deserializer for Gson? in order to learn more about custom deserializers.

提交回复
热议问题