简体   繁体   中英

Jackson Dynamic Json mapping with Class automatically

My json Object is dynamic, there may be arounf 10 -15 types of dynamic json response i will get,

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 );

Based on my above code the response always consider to take A.class and will throw an exception.

How can i identify the response belongs to specifc class, and convert it?

You can use a custom deserializer for this:

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();

  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM