杰克逊根据属性名称反序列化

时间:2018-05-22 06:14:52

标签: java json jackson jackson-databind

我有以下两种类型的JSON对象:

{"foo": "String value"}

{"bar": "String value"}

它们都代表同一基础对象的特殊类型。我如何使用杰克逊对它们进行反序列化?类型信息仅由键本身表示,而不是任何键的值(几乎所有示例都使用键的值来确定类型:https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization

3 个答案:

答案 0 :(得分:2)

杰克逊并没有提供out of the box solution,但这并不意味着你运气不好。

假设您的类实现了一个公共接口或扩展了一个公共类,如下所示:

public interface Animal {

}
public class Dog implements Animal {

   private String bark;

   // Default constructor, getters and setters
}
public class Cat implements Animal {

   private String meow;

   // Default constructor, getters and setters
}

您可以根据属性名称创建自定义反序列化程序。它允许您定义唯一属性,该属性将用于查找类以执行反序列化:

public class PropertyBasedDeserializer<T> extends StdDeserializer<T> {

    private Map<String, Class<? extends T>> deserializationClasses;

    public PropertyBasedDeserializer(Class<T> baseClass) {
        super(baseClass);
        deserializationClasses = new HashMap<String, Class<? extends T>>();
    }

    public void register(String property, Class<? extends T> deserializationClass) {
        deserializationClasses.put(property, deserializationClass);
    }

    @Override
    public T deserialize(JsonParser p, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {

        ObjectMapper mapper = (ObjectMapper) p.getCodec();
        JsonNode tree = mapper.readTree(p);

        Class<? extends T> deserializationClass = findDeserializationClass(tree);
        if (deserializationClass == null) {
            throw JsonMappingException.from(ctxt, 
               "No registered unique properties found for polymorphic deserialization");
        }

        return mapper.treeToValue(tree, deserializationClass);
    }

    private Class<? extends T> findDeserializationClass(JsonNode tree) {

        Iterator<Entry<String, JsonNode>> fields = tree.fields();
        Class<? extends T> deserializationClass = null;

        while (fields.hasNext()) {
            Entry<String, JsonNode> field = fields.next();
            String property = field.getKey();
            if (deserializationClasses.containsKey(property)) {
                deserializationClass = deserializationClasses.get(property);
                break;  
            }
        }

        return deserializationClass;
    }
}

然后实例化并配置反序列化器:

UniquePropertyPolymorphicDeserializer<Animal> deserializer = 
        new UniquePropertyPolymorphicDeserializer<>(Animal.class);

deserializer.register("bark", Dog.class); // If "bark" is present, then it's a Dog
deserializer.register("meow", Cat.class); // If "meow" is present, then it's a Cat

将其添加到模块:

SimpleModule module = new SimpleModule("custom-deserializers", Version.unknownVersion());
module.addDeserializer(Animal.class, deserializer);

注册模块并照常执行反序列化:

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);

String json = "[{\"bark\":\"bowwow\"}, {\"bark\":\"woofWoof\"}, {\"meow\":\"meeeOwww\"}]";
List<Animal> animals = mapper.readValue(json, new TypeReference<List<Animal>>() { });

答案 1 :(得分:2)

使用fasterxml jackson,您可以执行以下操作:

abstract class FooOrBar {
    companion object {
        @JvmStatic
        @JsonCreator
        private fun creator(json: Map<String, String>): FooOrBar? {
            return when {
                json.containsKey("foo") -> Foo(json["foo"] as String)
                json.containsKey("bar") -> Foo(json["bar"] as String)
                else -> null
            }
        }
    }
}

class Foo(val foo: String) : FooOrBar() // even can use map delegate if you know what it is
class Bar(val bar: String) : FooOrBar()

是科特林,但您会明白的。

请注意 使用@JsonCreator。带注释的creator函数具有单个参数(这是JsonCreator所需的两个签名中的一种),JSON被反序列化为Map实例并传递给creator。从这里,您可以创建您的类实例。

---------------- UPDATE -------------------------

对于嵌套复杂的JSON,您还可以将JsonNode用于creator函数。

private fun creator(json: JsonNode): FooOrBar?

答案 2 :(得分:0)

你必须告诉杰克森你期望什么课:

Foo readValue = mapper.readValue(json, Foo.class);

Bar readValue = mapper.readValue(json, Bar.class);

否则,如果您的设计需要强类型,则可能值得使用XML。