我的问题与Prevent GSON from serializing JSON string类似,但是那里的解决方案使用了GSON库,我只能使用Jackson(fastxml)。
我有一个实体类如下:
package com.dawson.model;
import com.dawson.model.audit.BaseLongEntity;
import lombok.extern.log4j.Log4j;
import javax.persistence.*;
@Table(name = "queue", schema = "dawson")
@Entity
@Log4j
public class Queue extends BaseLongEntity {
protected String requestType;
protected String body;
protected Queue() {
}
public Queue(String requestType, String body) {
this.requestType = requestType;
this.body = body;
}
@Column(name = "request_type")
public String getRequestType() {
return requestType;
}
public void setRequestType(String requestType) {
this.requestType = requestType;
}
@Column(name = "body")
@Lob
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
我想用地图的json字符串表示填充body字段,然后将其作为ResponseEntity的一部分发送。如下:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.writer().withDefaultPrettyPrinter();
HashMap<String, String> map = new HashMap<>(5);
map.put("inquiry", "How Can I solve the problem with Jackson double serialization of strings?");
map.put("phone", "+12345677890");
Queue queue = null;
try {
queue = new Queue("General Inquiry", mapper.writeValueAsString(map));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
String test = mapper.writeValueAsString(map)
System.out.println(test);
预期输出:"{"requestType": "General Inquiry","body": "{"inquiry":"How Can I solve the problem with Jackson double serialization of strings?","phone":"+12345677890"}"}"
实际输出:"{"requestType": "General Inquiry","body": "{\"inquiry\":\"How Can I solve the problem with Jackson double serialization of strings?\",\"phone\":\"+12345677890\"}"}"
我正在使用
Jackson Core v2.8.2
我尝试过玩
@JsonIgnore
和
@JsonProperty
标签,但这没有用,因为我的字段在写入实体时已经从地图序列化了。
答案 0 :(得分:4)
将@JsonRawValue
注释添加到body
属性。这使得Jackson将属性的内容视为文字JSON值,不应对其进行处理。
请注意,杰克逊不对该字段的内容进行任何验证,这使得生成无效的JSON变得非常容易。
答案 1 :(得分:-1)
使用此Jackson: how to prevent field serialization (while keeping deserialization)
@JsonIgnore
public String password;
@JsonIgnore
public String getPassword() {
return password;
}
@JsonProperty
public void setPassword(String password) {
this.password = password;
}