杰克逊:防止序列化通过序列化哈希映射获得的 json 字符串



我的问题有点类似于阻止 GSON 序列化 JSON 字符串,但那里的解决方案使用 GSON 库,我只能使用 Jackson (fasterxml(。

我有一个实体类,如下所示:

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 字符串表示形式填充正文字段,然后将其作为响应实体的一部分发送。 内容如下:

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"}"}"

我正在使用

杰克逊核心 v2.8.2

我试过玩

@JsonIgnore

@JsonProperty

标记,但这无济于事,因为我的字段在写入实体时已经从映射序列化。

@JsonRawValue批注添加到 body 属性。这使得 Jackson 将属性的内容视为不应处理的文本 JSON 值。

请注意,Jackson 不会对字段的内容进行任何验证,这使得生成无效的 JSON 非常容易。

最新更新