首页 > 解决方案 > 杰克逊动态 Json 与 Class 自动映射

问题描述

我的 json 对象是动态的,我会得到大约 10 -15 种动态 json 响应,

EX: {"a": "B"}, {"a": [a, c, d]}, {a:b, d: []}, {a: []}, {a: [], b:[]} 
these are possible types i have define.

//Before writing the below line, I have to identify the response belongs 
to the correct Class Type and Convert the response into the corosponding Java Class. 

A aResponse = mapper.convertValue(jsonResponse(), A.class );

根据我上面的代码,响应总是考虑采用 A.class 并且会抛出异常。

我如何识别响应属于特定类,并将其转换?

标签: javaserializationjackson

解决方案


您可以为此使用自定义反序列化器:

public class Test {
  public static void main(String[] args) throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    final SimpleModule module = new SimpleModule("configModule",   Version.unknownVersion());
    module.addDeserializer(Root.class, new DeSerializer());
    mapper.registerModule(module);
    Root readValue = mapper.readValue(<json source>);
  }
}

class DeSerializer extends StdDeserializer<Root> {

  protected DeSerializer() {
    super(Root.class);
  }

  @Override
  public Root deserialize(JsonParser p, DeserializationContext ctxt) throws Exception {
    // use p.getText() and p.nextToken to navigate through the json, conditionally check the tags and parse them to different objects and then construct Root object
    return new Root();

  }
}

推荐阅读