skip to Main Content

When I have a json below,

{
    "test1": "test123",
    "test2": {
        "a": 1,
        "b": 2
    }
}

I want to map this to below class using Jackson library.

class TestClass {
    String test1;
    String test2;
}

But I can’t do this because test2 is an json object, not String. I want to map both test1 and test2 to string

String test1; // "test123"
String test2; // "{"a": 1, "b": 2}"

What should I do?

2

Answers


  1. You should create java class with values that corresponds to you json object. In your case test1 is String object and test2 requires you to create new class that will hold two strings ‘a‘ and b. With your approach you will lose clear data access when converting two values into one String.

    Please refer to those links for more information

    Login or Signup to reply.
  2. Use custom deserializer.


    class TestClass {
        String test1;
        String test2;
    
        public TestClass(String test1, String test2) {
            this.test1 = test1;
            this.test2 = test2;
        }
    }
    

    public class MyDeserializer extends StdDeserializer<TestClass> {
    
        public MyDeserializer() {
            this(TestClass.class);
        }
    
        public MyDeserializer(Class<?> vc) {
            super(vc);
        }
    
        @Override
        public TestClass deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            JsonNode node = p.getCodec().readTree(p);
            return new TestClass(node.get("test1").asText(), node.get("test2").toString());
        }
    }
    

    Test

    String json = "{" +
            "    "test1": "test123"," +
            "    "test2": {" +
            "        "a": 1," +
            "        "b": 2" +
            "    }" +
            "}";
    ObjectMapper mapper = new ObjectMapper().registerModule(
            new SimpleModule().addDeserializer(TestClass.class, new MyDeserializer()));
    TestClass testClass = mapper.readValue(json, TestClass.class);
    System.out.println(testClass.test1);
    System.out.println(testClass.test2);
    

    Output

    test123
    {"a":1,"b":2}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search