简体   繁体   中英

Jackson json string -> object convert problem

I want to convert this string.

String str = "{ \"name\": \"\"shcheong\"\", \"age\": 27 }";

I expect to print name "shcheong" using jackson. but jackson can't convert and throw exception.

How can I convert to "shcheong".

======Edit======

add my code.

ObjectMapper mapper = new ObjectMapper();
TestDTO testDTO = mapper.readValue(str, TestDTO.class);
        
System.out.println(testDTO.getName());
System.out.println(testDTO.getAge());

And TestDTO.class

public TestDTO {
    private String name;
    private int age;

    ----via Getter and Setter----
}

I think the problem is about repeated quotes

\"\"shcheong\"\"

If you want to put " as a part of the JSON attribute, you have to double escape the character.

String str = "{ \"name\": \"\\\"shcheong\\\"\", \"age\": 27 }";

Or you can apply String.format to make code less verbose.

String str = String.format("{ \"name\": \"%s\", \"age\": 27 }", "\\\"shcheong\\\"")
ObjectMapper objectMapper = new ObjectMapper();

String human= "{ \"name\": \"\"shcheong\"\", \"age\": 27 }";

Human h = objectMapper.readValue(human, Human .class);

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