在Jackson中,无需使用注解将JSON反序列化为带引号的字符串。

huangapple go评论71阅读模式
英文:

Deserialize json as quoted string in Jackson without annotations

问题

我有一个类似这样的类。

class MyClass {
    String config;
    // ... 其他字段,getter,setter ...
}

config 字符串将作为 JSON 从 REST 端点的请求体中获取,格式如下。

"config": {
   "field1": "value1",
   "field2": 2,
   "field3": true
}
// MyClass 的其他字段

我需要对 MyClass 进行反序列化,使得上述 JSON 字符串以如下方式放入引号中。

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

由于这个类被其他项目使用,我不能修改它。因此,我不能在类上使用 @JsonDeserialize 或任何注解。

我尝试了将以下属性设置给 ObjectMapper

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

是否有其他方法,也许使用 ObjectMapper 来以这种方式进行反序列化?我也在使用 Spring Boot,所以欢迎使用 Spring Boot Jackson 的方式来处理这个问题。

英文:

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.

答案1

得分: 1

你可以使用JsonNode,这是Jackson库的JsonNode类,com.fasterxml.jackson.databind.JsonNode是Jackson用于JSON的树模型(对象图模型),使用方法如下:

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

You can use JsonNode, the Jackson JsonNode class, com.fasterxml.jackson.databind.JsonNode is Jackson's tree model (object graph model) for JSON, use like that:

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

huangapple
  • 本文由 发表于 2020年9月26日 00:07:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/64067691.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定