【问题标题】:Selective usage of @JsonCreator@JsonCreator 的选择性使用
【发布时间】:2014-07-03 20:33:47
【问题描述】:

我有一个 POJO,例如

public class Category {
    public Collection<Item> items;
    public static class Item {
        public String firstAttribute;
        public int value;
    }
}

我正在使用以下内容从 json 输入转换为 POJO(Category):

JsonNode results = mapper.readTree(connection.getInputStream());

mapper.convertValue(results, Category.class));

这一切都很好,并且按预期工作。但是,输入 JSON 偶尔会包含布尔值 false 而不是实际的项目对象。 JSON 类似于以下内容:

{
    "id":1, 
    "items": [
        {
            "firstAttribute": "Test 1",
            "value": 1
        },
        {
            "firstAttribute": "Test 2",
            "value": 2
        },
        {
            "firstAttribute": "Test 3",
            "value": 3
        },
        false,
        false,
        false,
        {
            "firstAttribute": "Test 4",
            "value": 4
        },
        false,
        {
            "firstAttribute": "Test 5",
            "value": 5
        },
    ]
}

布尔值抛出解析器,使其抛出异常

java.lang.IllegalArgumentException: Can not instantiate value of type [simple type, class com.example.test.Category$Item] from JSON boolean value; no single-boolean/Boolean-arg constructor/factory method

我试图通过使用@JsonCreator 来解决这个问题

public class Category {
    public int id;
    public Collection<Item> items;
    public static class Item {
        public String firstAttribute;
        public int value;
        @JsonCreator public static Item Parse(JsonNode node) {
            if (node.isBoolean()) {
                return null;
            }

            else {
                // use default Jackson parsing, as if the method 'Parse' wasn't there
            }
        }
    }
}

这几乎就是我卡住的地方。我一直无法弄清楚如何调用默认的 Jackson Deserializer,.当然,我可以自己简单地检索和设置值,但是,在我正在构建的实际项目中,有大量复杂的模型,以及各种不一致的 json 输入,我宁愿避免解析所有内容手动。

【问题讨论】:

    标签: android json jackson pojo


    【解决方案1】:

    不幸的是,这是有效的 JSON,这应该可以解决问题:

    public class Category {
        private Integer id;
        private Collection<Item> items = Lists.newArrayList();
    
        @JsonCreator
        public Category(@JsonProperty("id") Integer id, 
                        @JsonProperty("items") ArrayNode nodes) {
            this.id = id;
            for (int i = 0; i < nodes.size(); i++) {
                JsonNode node = nodes.get(i);
                if (!node.isBoolean()) {
                    items.add(objectMapper.readValue(node, Item.class));
                }
            }
        }
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 2020-01-29
      • 1970-01-01
      • 1970-01-01
      • 2012-04-27
      • 2013-01-29
      • 2021-01-31
      • 2015-12-29
      • 1970-01-01
      • 2017-12-16
      相关资源
      最近更新 更多