杰克逊:根据野外存在选择儿童类进行反序列化

时间:2017-02-20 15:16:03

标签: java json jackson deserialization json-deserialization

我有以下型号:

public abstract class A {
    String commonField;
}

public class B extends A {    
}

public class C extends A {
    String customField;
}

如何根据存在选择班级(B或C)' customField'场?

{ "commonField" : "..."} --> B instance

{ "commonField" : "...", "customField" : null} --> B instance

{ "commonField" : "...", "customField" : "..."} --> C instance

3 个答案:

答案 0 :(得分:1)

我发现反序列化为Map()并迭代键非常简单,特别是使用Jackson API

ObjectMapper mapper = new ObjectMapper();
Map<String, String> map = mapper.readValue(jsonString, Map.class);
for(String key : map.keySet)
{
    if(key.equals("customField")
    {
        // do your stuff
    }
}

答案 1 :(得分:1)

试试这可以是任何帮助

ObjectMapper mapper = new ObjectMapper();

String json = "{ \"commonField\" : \"...\", \"customField\"}";

JsonNode jsonNode = mapper.readTree( json );

A a; // class a

if(jsonNode.has( "customField" )) {

    a = mapper.convertValue( jsonNode, C.class );           
} else {

    a = mapper.convertValue( jsonNode, B.class );
}

答案 2 :(得分:0)

您可以为自己的案例编写自己的反序列化程序,并在ObjectMapper中使用其他模块或@JsonDeserialize上的A注释进行注册。

例如:

public class ADeserializer extends StdDeserializer<A> {
    public ADeserializer() {
        super(A.class);
    }

    @Override
    public A deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        JsonNode node = p.readValueAsTree();
        JsonNode customField = node.findValue("customField");
        A result;
        if (customField != null && !customField.isNull()) {
            result = new C();
            ((C)result).customField = customField.asText();
        } else {
            result = new B();
        }
        result.commonField = node.findValue("commonField").asText();
        return result;
    }
}

并使用新模块注册:

@Test
public void test() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addDeserializer(A.class, new ADeserializer());
    mapper.registerModule(module);

    String jsonB = "{\"commonField\" : \"value\"}";
    Assert.assertTrue(mapper.readValue(jsonB, A.class) instanceof B);
    String jsonBNull = "{\"commonField\" : \"value\", \"customField\" : null}";
    Assert.assertTrue(mapper.readValue(jsonBNull, A.class) instanceof B);
    String jsonC = "{\"commonField\" : \"value\", \"customField\" : \"anotherValue\"}";
    Assert.assertTrue(mapper.readValue(jsonC, A.class) instanceof C);
}