How to handle different data types with same attribute name with Gson?

前端 未结 4 1538
北恋
北恋 2020-12-10 04:31

I\'m currently writing an RSS feed parser in Java utilizing Gson. I\'m converting the RSS\' XML into JSON, and then subsequently using Gson to deserialize the JSON into Java

4条回答
  •  悲&欢浪女
    2020-12-10 05:25

    My answer is to make use of a class hierarchy.

    abstract class Guid {
        private boolean isPermalink;
        private String content;
        // getters and setters omitted
    }
    
    class GuidObject extends Guid {} 
    class GuidString extends Guid {}
    
    class RssFeedItem {
        // super class to receive instances of sub classes
        private Guid guid; 
    }
    

    And register a deserializer for Guid:

    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(Guid.class, new JsonDeserializer() {
            @Override
            public Guid deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                // Dispatch based on the type of json
                if (json.isJsonObject()) {
                    // If it's an object, it's essential we deserialize
                    // into a sub class, otherwise we'll have an infinite loop
                    return context.deserialize(json, GuidObject.class);
                } else if (json.isJsonPrimitive()) {
                    // Primitive is easy, just set the most
                    // meaningful field. We can also use GuidObject here
                    // But better to keep it clear.
                    Guid guid = new GuidString();
                    guid.setContent(json.getAsString());
                    return guid;
                }
                // Cannot parse, throw exception
                throw new JsonParseException("Expected Json Object or Primitive, was " + json + ".");
            }
        });
    

    This way you can potentially handle much more complex JSON objects, and dispatch based on whatever criteria you like.

提交回复
热议问题