简体   繁体   中英

How to convert json object string to plain string using jackson?

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?

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

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}

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