简体   繁体   中英

Deserialize json as quoted string in Jackson without annotations

I have a class like this.

class MyClass {
    String config;
    // ... other fields, getters, setters ...
}

The config string will be coming as JSON from the REST endpoint in the request body as follows..

"config": {
   "field1": "value1",
   "field2": 2,
   "field3": true
}
// other fields of MyClass

I need to deserialize MyClass in such a way that the above JSON string is put in quotes as follows.

"config": "{
   \"field1\": \"value1\",
   \"field2\": 2,
   \"field3\": true
}"

I cannot modify this class as it is being used by other projects. So, I cannot use @JsonDeserialize or any annotations on the class.

I tried setting the following properties to ObjectMapper

 mapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, false)
 .configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);

Is there any other way, perhaps using ObjectMapper to deserialize it that way. I am using Spring Boot also, so would welcome a Spring boot Jackson way of doing this.

您可以使用JsonNode,Jackson JsonNode 类,com.fasterxml.jackson.databind.JsonNode 是Jackson 的JSON 树模型(对象图模型),像这样使用:

String content = jsonNode.get("data").textValue();

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