有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JAVA是否可以过滤大型递归JSON对象的子元素??

我需要一些帮助来快速解决我的问题。给定一个json对象,该对象很大,具有递归模型。我想列出JSON子元素&;其直接父对象(仅满足给定键值条件的子对象)

 Ex :   
{
Object : {
   id : "0001",
   parent:"A",
   child: {
       id:"0001A",
       Country:"US",
       parent:"B",
       child:{
         id:"0001AA",
         Country:"UK",
         parent:"C",
         child:{
            id:"0000AAA",
            Country:"US",
            parent:"D",
            child:{
                .........
            }
         }
       }
   }
}

}

我想列出其国家为“US”的子对象的id及其父id。。 是否有现成的插件可以在JAVA中处理此类场景,而不使用对象映射器/自定义类对象。。 请提供任何可能的想法


共 (1) 个答案

  1. # 1 楼答案

    是的,可以使用the Jackson Tree Model API编写代码,它将遍历JSON树并选择满足条件的节点。下面是一个例子:

    public class JacksonTree2 {
        public static final String JSON = "{\"Ex\" :   {\"Object\" : {\n" +
                "   \"id\" : \"0001\",\n" +
                "   \"parent\":\"A\",\n" +
                "   \"child\": {\n" +
                "       \"id\":\"0001A\",\n" +
                "       \"Country\":\"US\",\n" +
                "       \"parent\":\"B\",\n" +
                "       \"child\":{\n" +
                "         \"id\":\"0001AA\",\n" +
                "         \"Country\":\"UK\",\n" +
                "         \"parent\":\"C\",\n" +
                "         \"child\":{\n" +
                "            \"id\":\"0000AAA\",\n" +
                "            \"Country\":\"US\",\n" +
                "            \"parent\":\"D\",\n" +
                "            \"child\":{\n" +
                "                \n" +
                "            }\n" +
                "         }\n" +
                "       }\n" +
                "\t}\n" +
                "}}}";
    
        public static void main(String[] args) throws IOException {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode root = mapper.readTree(JSON);
            for (JsonNode node : root.findParents("Country")) {
                if ("UK".equals(node.get("Country").asText())) {
                    System.out.println(node.get("id"));
                    break;
                }
            }
        }
    
    }
    

    输出:

    "0001AA"