我看到人们使用toString()
来获取JsonNode的文本值,当它是一个ObjectNode
而不是一个ValueNode
时,特别是当某个节点的内容也是一个JSON字符串时;我们可以构造另一个JsonNode来更深入地遍历内部树。
JsonNode shippingInfo = null;
JsonNode brand = null;
ArrayNode included = (ArrayNode)details.get("included");
for (JsonNode node: included) {
if ("offers".equals(node.get("type").asText()) &&
orderOffer.getOfferId().toString().equals(node.get("id").asText())) { // asText() will return empty string "", because it is not ValueNode.
shippingInfo = node.get("attributes").get("shippingSellerMethod");
} else if ("brands".equals(node.get("type").asText())) {
brand = node.get("attributes");
}
}
我知道它很有用,但很丑陋。我想知道是否有另一种更像杰克逊的方式来获得价值,并不总是get(node_name).toString()
。
您可以将 JSOn 解读为Map
:
var map = new ObjectMapper().readValue(json, Map.class);
for (var node : ((Map<String, List<Map<String, Object>>>) map).get("included")) {
if ("offers".equals(node.get("type")) && orderOffer.getOfferId().equals(node.get("id"))) {
shippingInfo = ((Map<String, String>)node.get("attributes")).get("shippingSellerMethod");
}
}
另一种方法是将数据描述为类:
class InputData {
@JsonProperty
List<Details> included;
}
class Details {
@JsonProperty
int id;
@JsonProperty
String type;
@JsonProperty
Map<String, Object> attributes;
}
并按以下方式阅读:
var parsed = mapper.readValue(json, InputData.class);
for (Details details : parsed.included) {
if (details.type.equals("offers") && details.id == 1) {
shippingInfo = details.attributes.get("shippingSellerMethod")
}
}
接下来是使用JsonTypeInfo
和JsonSubTypes
注释。