使用杰克逊生成带有反斜线的json

时间:2018-09-19 05:15:12

标签: json apache-kafka kafka-producer-api spring-kafka jackson-databind


我正在使用Jackson库生成json。 Jackson正在以以下格式生成json。

{"color":"yellow","type":"renault"}

我想使用反斜杠生成上述格式,如下所示:

{\"color\":\"yellow\",\"type\":\"renault\"}

在我使用kafka流API进行转换时,需要带反斜杠的格式。

这是我的模特班:

public class Car {

    private String color;
    private String type;

    public Car() {
    }

    public Car(final String color, final String type) {
        this.color = color;
        this.type = type;
    }

    public String getColor() {
        return color;
    }

    public void setColor(final String color) {
        this.color = color;
    }

    public String getType() {
        return type;
    }

    public void setType(final String type) {
        this.type = type;
    }
}

请让我知道我需要做哪些配置/属性更改,以便以上述所需格式生成json。

我还附加了屏幕截图,以显示其余代码。

谢谢!

code screenshot

1 个答案:

答案 0 :(得分:0)

使用JsonStringEncoder。

这是示例代码:

JsonStringEncoder e = JsonStringEncoder.getInstance();         String jsonString = new String(e.quoteAsString(objectMapper.writeValueAsString(car)));

相关问题