【问题标题】:generate json with backslash using jackson使用jackson生成带反斜杠的json
【发布时间】:2019-02-23 04:43:48
【问题描述】:

.
我正在使用杰克逊库来生成 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

【问题讨论】:

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


    【解决方案1】:

    使用 JsonStringEncoder。

    这里是示例代码:

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

    【讨论】:

      猜你喜欢
      • 2015-10-08
      • 2015-05-26
      • 2014-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-05
      • 1970-01-01
      • 2017-10-01
      相关资源
      最近更新 更多