简体   繁体   English

正确的 Jackson 获取 JsonNode 文本值的方法

[英]Correct Jackson way to get the text value of a JsonNode

I see people using toString() to get the text value of a JsonNode, when it is a ObjectNode instead of a ValueNode , especially when the content of some node is a JSON string as well;我看到人们使用toString()来获取 JsonNode 的文本值,当它是ObjectNode而不是ValueNode ,尤其是当某些节点的内容也是 JSON 字符串时; we may construct another JsonNode to traverse deeper into the inner tree.我们可以构造另一个 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");
    }
}

I understand it is useful but ugly.我知道它很有用但很丑。 I want to know if there is another more Jackson-ish way to get the value, not always get(node_name).toString() .我想知道是否有另一种更杰克逊风格的方法来获取值,而不总是get(node_name).toString()

You may read the JSOn as Map :您可以将 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");
    }
}

Another approach is to describe your data as classes:另一种方法是将您的数据描述为类:

class InputData {
    @JsonProperty
    List<Details> included;
}

class Details {
    @JsonProperty
    int id;
    @JsonProperty
    String type;
    @JsonProperty
    Map<String, Object> attributes;
}

and to read it in the following way:并以下列方式阅读它:

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")
    }
}

The next would be to use JsonTypeInfo and JsonSubTypes annotations.接下来是使用JsonTypeInfoJsonSubTypes注释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM