【问题标题】:Jackson and Gson inconsistent for deserialization?Jackson 和 Gson 反序列化不一致?
【发布时间】:2015-03-18 17:47:46
【问题描述】:

我观察到关于 Jackson 和 Gson 允许换行符出现在 JSON 对象的字符串表示中的方式不一致的行为。请考虑以下最小示例。

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;

import java.io.IOException;

public class GsonTest {
    public static void main(String[] args) throws IOException {

        //Json string with a literal newline
        String jsonString1 = "{\"text\":\"123\nabc\"}";

        // Parse jsonString1 with Jackson
        ObjectMapper mapper = new ObjectMapper();
        // System.out.println(mapper.readValue(jsonString1, TestObj.class)); // produces JsonMappingException, uncomment to run

        // Parse jsonString1 with Gson
        Gson gson = new Gson();
        System.out.println(gson.fromJson(jsonString1, TestObj.class)); // parses fine

        // Json string with escaped newline
        String jsonString2 = "{\"text\":\"123\\nabc\"}";

        // Parse jsonString2 with Jackson
        System.out.println(mapper.readValue(jsonString2, TestObj.class)); // parses fine

        // Parse jsonString2 with Gson
        System.out.println(gson.fromJson(jsonString2, TestObj.class)); // parses fine

    }
}

class TestObj {
    public String text;

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
}

我的问题是:

  1. jsonString1 是有效的 JSON 吗?
  2. 如果是,为什么 Jackson 无法解析?
  3. 如果不是,为什么 Gson 允许对其进行解析?

谢谢。

【问题讨论】:

    标签: json jackson gson


    【解决方案1】:

    这一行:

    String jsonString1 = "{\"text\":\"123\nabc\"}";
    

    用字符创建一个字符串

    {"text":"123<newline>abc"}
    

    其中的真的是一个换行符。

    JSON 规范要求字符串中的换行符必须转义为 \n,因此 jsonString1 不包含有效的 JSON,解析器应该拒绝它。要创建包含字符 \n 的字符串,您的源代码应该是

    String jsonString1 = "{\"text\":\"123\\nabc\"}";
    

    所以源代码包含一个转义的反斜杠,后跟一个 n。该字符串将包含一个反斜杠,后跟一个 n,JSON 解析器会将其解析为换行符。

    【讨论】:

    • 现在问题 3 怎么样:为什么 Gson 会错误地解析这个 JSON 而不是拒绝它
    • 我猜 GSON 只是没有将其视为错误情况(或不在乎)。根据规范,它是无效的 JSON。您可能想要提交错误报告,以便 GSON 开发人员可以在适当检查时选择?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-11
    • 1970-01-01
    • 2019-04-10
    • 2019-01-05
    相关资源
    最近更新 更多