【问题标题】:Why org.json.JSONObject excludes POJO fields start with x while converting to JSON object?为什么 org.json.JSONObject 在转换为 JSON 对象时排除以 x 开头的 POJO 字段?
【发布时间】:2022-01-18 00:31:11
【问题描述】:

将包含以“x”开头的字段的对象映射到org.json.JSONObjectcom.fasterxml.jackson.core.ObjectMapper 时会出现不同的结果:

JSONObject

{"one":"One"}

ObjectMapper

{"one":"One","xOne":"xOne"}

为什么JSONObject 不包含“xOne”字段?

public class Test {
    
    private String one;
    private String xOne;

    public String getOne() {
        return one;
    }

    public void setOne(String one) {
        this.one = one;
    }

    public String getxOne() {
        return xOne;
    }

    public void setxOne(String xOne) {
        this.xOne = xOne;
    }

    @Override
    public String toString() {
        return "Test [one=" + one + ", xOne=" + xOne + "]";
    }

}

public class PojoToJson {

    public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
        Test test = new Test();
        test.setOne("One");
        test.setxOne("xOne");
        JSONObject json = new JSONObject(test);
        System.out.println("JSONObject o/p: " + json);

        ObjectMapper mapper = new ObjectMapper();
        String mapperString = mapper.writeValueAsString(test);
        System.out.println("ObjectMapper o/p: " + mapperString);
    }
}

这是我使用JSONObjectObjectMapper 的输出差异:

【问题讨论】:

  • getxOne() 可能不会被视为吸气剂。请尝试重命名为 getXOne()
  • 有趣...这些是自动生成的 setter 和 getter,如果您有超过 50 个变量,很难手动完成。
  • @gwell 成功了...您可能希望将您的评论转化为答案
  • @gwell 所以这里的结论是 ObjectMapper 正在检查不区分大小写的 getter 名称,而 JSONObject 有严格的 getter 检查?
  • FWIW,Jackson 有自己的 JSONObject 类,不应该使用 org.json 导入

标签: java json jackson-databind


【解决方案1】:

根据Jackson reference documentation

在没有注册自定义策略的情况下,默认的 Java 属性 使用命名策略,保留字段名称,并删除 set/get/is 方法的前缀(以及小写的首字母) 大写字符序列)。

据我了解,这意味着杰克逊会明白 getxOne() 实际上对应于 xOne 属性。

org.json.JSONObject 可能有不同的命名策略(我无法在任何地方找到),因此 getxOne() 与 Jackson 的 ObjectMapper 一起使用而不是与 org.json.JSONObject 一起使用的原因。

【讨论】:

  • 另一种可能性,我需要解决这个问题以确定是否是这种情况,是杰克逊不理解getxOne,而是使用字段名称来确定映射.不过,你很可能是对的。
  • 也可能是这样。 Jackson 遗漏了一些示例,以便我们确定get 之后的第一个字母为小写时的行为。
  • 它很容易测试,但我现在没有地方可以用它。
猜你喜欢
  • 2015-02-17
  • 2022-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-13
  • 1970-01-01
相关资源
最近更新 更多