Convert JsonNode into POJO

后端 未结 4 1024
梦毁少年i
梦毁少年i 2020-11-30 20:24

This may seem a little unusual, but I am looking for an efficient way to transform/map a JsonNode into a POJO.

I store some of my Model\'s

4条回答
  •  遥遥无期
    2020-11-30 21:00

    This should do the trick:

    mapper.readValue(fileReader, MyClass.class);
    

    I say should because I'm using that with a String, not a BufferedReader but it should still work.

    Here's my code:

    String inputString = // I grab my string here
    MySessionClass sessionObject;
    try {
        ObjectMapper objectMapper = new ObjectMapper();
        sessionObject = objectMapper.readValue(inputString, MySessionClass.class);
    

    Here's the official documentation for that call: http://jackson.codehaus.org/1.7.9/javadoc/org/codehaus/jackson/map/ObjectMapper.html#readValue(java.lang.String, java.lang.Class)

    You can also define a custom deserializer when you instantiate the ObjectMapper: http://wiki.fasterxml.com/JacksonHowToCustomDeserializers

    Edit: I just remembered something else. If your object coming in has more properties than the POJO has and you just want to ignore the extras you'll want to set this:

        objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    

    Or you'll get an error that it can't find the property to set into.

提交回复
热议问题