Jackson: Deserialize to a Map with correct type for each value

前端 未结 1 571
庸人自扰
庸人自扰 2020-12-16 09:49

I have a class that looks like the following

public class MyClass {
   private String val1;
   private String val2;
   private Map conte         


        
相关标签:
1条回答
  • 2020-12-16 10:14

    I think the simplest way of achieve what you want is using:

    ObjectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    

    This will add type information in the serialized json.

    Here you are a running example, that you will need to adapt to Spring:

    public class Main {
    
        public enum MyEnum {
            enumValue1
        }
    
        public static void main(String[] args) throws IOException {
            ObjectMapper mapper = new ObjectMapper();
    
            MyClass obj = new MyClass();
            obj.setContext(new HashMap<String, Object>());
    
            obj.setVal1("foo");
            obj.setVal2("var");
            obj.getContext().put("key1", "stringValue1");
            obj.getContext().put("key2", MyEnum.enumValue1);
            obj.getContext().put("key3", 3.0);
    
            mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
            String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
    
            System.out.println(json);
    
            MyClass readValue = mapper.readValue(json, MyClass.class);
            //Check the enum value was correctly deserialized
            Assert.assertEquals(readValue.getContext().get("key2"), MyEnum.enumValue1);
        }
    
    }
    

    The object will be serialized into something similar to:

    [ "so_27871226.MyClass", {
      "val1" : "foo",
      "val2" : "var",
      "context" : [ "java.util.HashMap", {
        "key3" : 3.0,
        "key2" : [ "so_27871226.Main$MyEnum", "enumValue1" ],
        "key1" : "stringValue1"
      } ]
    } ]
    

    And will be deserialized back correctly, and the assertion will pass.

    Bytheway there are more ways of doing this, please look at https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization for more info.

    I hope it will help.

    0 讨论(0)
提交回复
热议问题