如何使用 Jackson TreeNode 和 JsonNode 提取我想要的 JSON 字段



我有点困惑为什么我不能从我的 JSON 流中提取"类型"字段来做出决定。 看来这应该很容易。我有以下 JSON 作为输入:

[
{
"Institution":"ABC",
"Facility":"XYZ",
"Make":"Sunrise",
"Model":"Admission",
"SerialNumber":"",
"Revision":"1",
"Type":"ABC_Admission",
"ArchiveData":"<CSV file contents>"
}
]

在我的Java中,我有一个带有JsonHolder类的try-catch块,该类实现Serializable来保存JSON。 这是我目前拥有的Java:

try {
// Parse and split the input
JsonHolder data = JsonHolder.getField("text", input);
DataExtractor.LOG.info("JsonHolder data= " + data);
TreeNode node = data.getTreeNode();
DataExtractor.LOG.info("node size= " + node.size());
node = node.path("Type");
JsonNode json = (JsonNode) node;
DataExtractor.LOG.info("json= " + json.asText());
// code to decide what to do based on Type found
if (json.asText().equals("ABC_Admission")) {
 // do one thing
} else {
 // do something else
}
} catch (IOException iox) {
DataExtractor.LOG.error("Error extracting data", iox);
this.collector.fail(input);
}

当我运行我的代码时,我得到以下输出(注意:我将类所在的包名称更改为仅用于此输出显示)

25741 [Thread-91-DataExtractor] INFO <proprietary package name>.DataExtractor - JsonHolder data= [
{
"Institution":"ABC",
"Facility":"XYZ",
"Make":"Sunrise",
"Model":"Admission",
"SerialNumber":"",
"Revision":"1",
"Type":"ABC_Admission",
"ArchiveData":"<CSV file contents>"
}
]
25741 [Thread-91-DataExtractor] INFO <proprietary package name>.DataExtractor - node size= 1
25741 [Thread-91-DataExtractor] INFO <proprietary package name>.DataExtractor - json=

正如你所看到的,我什么也没得到。 我只想提取字段"Type"的值,所以我希望在这种情况下获得值"ABC_Admission"。 我本以为节点路径会将该字段与 JSON 树的其余部分分开。
我做错了什么?

在咨询了另一位开发人员后,我发现问题是我的 JSON 在数组中。 因此,我需要遍历该数组,然后从对象中提取 Type 字段。

解决此问题的更新代码如下:

        try {
            // Parse and split the input
            JsonHolder data = JsonHolder.getField("text", input);
            DataExtractor.LOG.info("JsonHolder data= " + data);
            TreeNode node = data.getTreeNode();
            String type = null;
            // if this is an array of objects, iterate through the array
            // to get the object, and reference the field we want
            if (node.isArray()){
                ArrayNode ary = (ArrayNode) node;
                for (int i = 0; i < ary.size(); ++i) {
                    JsonNode obj = ary.get(i);
                    if (obj.has("Type")) {
                        type = obj.path("Type").asText();
                        break;
                    }
                }
            }
            if (type == null) {
               // Do something with failure??
            }
            DataExtractor.LOG.info("json= " + type);
            if (type.equals("ABC_Admission")) {
             // do one thing
            else {
             // do something else
            }
        } catch (IOException iox) {
            DataExtractor.LOG.error("Error extracting data", iox);
            this.collector.fail(input);
        }   

相关内容

最新更新