Jackson:防止序列化哈希图获得的json字符串的序列化

DPa*_*ncs 1 java serialization json jackson

我的问题有点类似于防止 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想用地图的 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);
Run Code Online (Sandbox Code Playgroud)

预期输出: "{"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

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

Hen*_*sen 5

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

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