gpt4 book ai didi

android - @JsonCreator 的选择性使用

转载 作者:行者123 更新时间:2023-11-29 01:41:14 32 4
gpt4 key购买 nike

我有一个 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 偶尔会包含 bool 值 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
},
]
}

bool 值抛出解析器,使其抛出异常

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 输入,我宁愿避免解析所有内容手动。

最佳答案

不幸的是,这是有效的 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));
}
}
}
...
}

关于android - @JsonCreator 的选择性使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24562868/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com