我是Jackson Streaming API的新手。
我想动态地从以下JSON
对象中读取值数组。
{
"jsonAry": [
{
"key1": "val1",
"key2": "val2"
},
{
"key3": "val3",
"key4": "val4"
}
]
}
答案 0 :(得分:0)
阅读this article后,您可以通过以下方式对其进行反序列化:
ObjectMapper mapper = new ObjectMapper();
JsonFactory f = new JsonFactory();
JsonParser jp = f.createParser(JSON);
//Skip all tokens before start array token.
while (jp.nextToken() != JsonToken.START_ARRAY) {
}
MapType mapType = mapper.getTypeFactory().constructMapType(Map.class, String.class, String.class);
while (jp.nextToken() != JsonToken.END_ARRAY) {
Map<String, String> map = mapper.readValue(jp, mapType);
System.out.println(map);
}
下一个选项是使用JsonNode
:
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(JSON);
JsonNode arrayNode = rootNode.get("jsonAry");
Iterator<JsonNode> jsonNodeIterator = arrayNode.elements();
while (jsonNodeIterator.hasNext()) {
JsonNode itemNode = jsonNodeIterator.next();
Iterator<String> fieldNames = itemNode.fieldNames();
while (fieldNames.hasNext()) {
String field = fieldNames.next();
System.out.println(field + " = " + itemNode.get(field));
}
}
如果您的JSON
不大,可以将其反序列化为POJO
。例如:
class JsonRoot {
@JsonProperty("jsonAry")
private List<JsonEntity> entities;
public List<JsonEntity> getEntities() {
return entities;
}
public void setEntities(List<JsonEntity> entities) {
this.entities = entities;
}
@Override
public String toString() {
return "JsonRoot{" +
"entities=" + entities +
'}';
}
}
class JsonEntity {
private Map<String, String> values = new LinkedHashMap<String, String>();
public Map<String, String> getValues() {
return values;
}
@JsonAnySetter
public void setValues(String key, String value) {
values.put(key, value);
}
@Override
public String toString() {
return "JsonEntity{" +
"values=" + values +
'}';
}
}
反序列化看起来像这样:
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.readValue(JSON, JsonRoot.class));