获取JSON中可变深度的ID列表

huangapple go评论102阅读模式
英文:

Java - Get list of id's from JSON with a variable depth

问题

我试图构建多个子树的id列表,例如我需要:\n- 1, 3, 6\n- 1, 4\n- 1, 5\n- 2, 7, 8, 9\n- 2, 7, 10, 11\n\n我之前开发了一个遍历整个树的例程(递归),使用了jackson库的功能和对象,不知道我是否可以将其适应到这个用例。\n\n有没有一种方法来构建这些列表并修改我的例程来实现它或者其他方法(另一个例程,...)\n\n谢谢

英文:

I have a JSON file with a fluctuating depth and each node (different depth). So it's built like a General tree :

获取JSON中可变深度的ID列表

And here is a sample json (not the real one but a mock file but the structure remains the same) :

  1. {
  2. "arbre" : {
  3. "children" : [
  4. {
  5. "id" : 1,
  6. "children" : [
  7. {
  8. "id" : 3,
  9. "children" : [
  10. {
  11. "id" : 6,
  12. "children" : []
  13. }
  14. ]
  15. },
  16. {
  17. "id" : 4,
  18. "children": []
  19. },
  20. {
  21. "id" : 5,
  22. "children": []
  23. }
  24. ]
  25. },
  26. {
  27. "id" : 2,
  28. "children" : [
  29. {
  30. "id" : 7,
  31. "children" :
  32. [
  33. {
  34. "id" : 8,
  35. "children" : [
  36. {
  37. "id" : 9,
  38. "children" : []
  39. }
  40. ]
  41. },
  42. {
  43. "id" : 10,
  44. "children" : [
  45. {
  46. "id" : 11,
  47. "children" : []
  48. }
  49. ]
  50. }
  51. ]
  52. }
  53. ]
  54. }
  55. ]
  56. }
  57. }

I'm trying to build multiple list of id for each subtrees, so for exemple I need :

  • 1, 3, 6
  • 1, 4
  • 1, 5
  • 2, 7, 8, 9
  • 2, 7, 10, 11

I previously developped a routine that traverse the entire tree (recursive) using jackson and don't know if I can adapt it to this use case.

Here it is :

  1. /**
  2. * getJSONNode: not return value, recursive function that will browse (uses functionalities and objects of the com.fasterxml.jackson library)
  3. *
  4. *
  5. * {talendTypes} String, JsonNode
  6. *
  7. * {Category} User Defined
  8. *
  9. * {param} JsonNode(jNode) input: the function will check if the node is an array of object and will process and keep iterate until it reaches the bottom of the tree
  10. * {param} string(filepath) input: The string is a path to a directory where the temp files will be stored
  11. *
  12. * {example} getJSONNode(jNode, "/test/") # Files will be generated in the directory /test/
  13. */
  14. public static void getJSONNode(JsonNode jNode, String filepath) throws IOException {
  15. //System.out.println("Get Node");
  16. JsonNode tempNoded = jNode.get("children");
  17. if(tempNoded.isArray()) {
  18. for(int i = 0; i < tempNoded.size(); i++) {
  19. System.out.println("Name : " + tempNoded.get(i).get("name"));
  20. System.out.println("Title : " + tempNoded.get(i).get("title"));
  21. System.out.println("Title : " + tempNoded.get(i).get("id"));
  22. System.out.println("================== Writing file ===================");
  23. String id = tempNoded.get(i).get("id").toString();
  24. String name = tempNoded.get(i).get("name").toString();
  25. String title = tempNoded.get(i).get("title").toString();
  26. String color = tempNoded.get(i).get("color").toString();
  27. String order = tempNoded.get(i).get("order").toString();
  28. String parentId = tempNoded.get(i).get("parentId").toString();
  29. String persons = tempNoded.get(i).get("persons").toString();
  30. String profils = tempNoded.get(i).get("profils").toString();
  31. String paramNoeud = tempNoded.get(i).get("paramNoeud").toString();
  32. String description = tempNoded.get(i).get("description").toString();
  33. // disable not present in all dimensions so not usable
  34. //String disabled = tempNoded.get(i).get("disabled").toString();
  35. String oldId = tempNoded.get(i).get("oldId").toString();
  36. String str = id + ";" + name + ";" + title + ";" + color + ";" + order + ";" + parentId + ";" + persons + ";" + profils + ";" + paramNoeud + ";" + description + ";" + oldId;
  37. byte[] strToBytes = str.getBytes();
  38. String filename = (name + "_" + order + ".csv").replaceAll("\"", "");
  39. File file = new File(filepath + filename);
  40. file.getParentFile().mkdirs();
  41. file.createNewFile();
  42. FileOutputStream outputStream = new FileOutputStream(filepath + filename);
  43. outputStream.write(strToBytes);
  44. outputStream.close();
  45. getJSONNode(tempNoded.get(i), filepath);
  46. }
  47. }
  48. }

So is there a method to build those lists and modify my routine to do it or something else (another routine, ...)

Thanks

答案1

得分: 1

我建议使用递归解决方案,跟踪当前子树:

  1. publi List<List<String>> getSubtrees(JsonNode childrenNode, List<String> currentSubtree) {
  2. ArrayList<List<String>> subtrees = new ArrayList<>();
  3. if (childrenNode.isEmpty()) {
  4. subtrees.add(currentSubtree);
  5. } else {
  6. for (JsonNode node : childrenNode) {
  7. String id = node.get("id").asText();
  8. JsonNode children = node.get("children");
  9. List<String> childSubtree = new ArrayList<>(currentSubtree);
  10. childSubtree.add(id);
  11. subtrees.addAll(getSubtrees(children, childSubtree));
  12. }
  13. }
  14. return subtrees;
  15. }

调用方式:

  1. List<List<String>> subtrees = getSubtrees(children, List.of());

其中children是顶级子节点的数组节点,在你的情况下是一个arbre -> children的JSON节点。这只是一个示例,请注意类型/空检查。

英文:

I would suggest a recursive solution that keeps track of current subtree:

  1. publi List&lt;List&lt;String&gt;&gt; getSubtrees(JsonNode childrenNode, List&lt;String&gt; currentSubtree) {
  2. ArrayList&lt;List&lt;String&gt;&gt; subtrees = new ArrayList&lt;&gt;();
  3. if (childrenNode.isEmpty()) {
  4. subtrees.add(currentSubtree);
  5. } else {
  6. for (JsonNode node : childrenNode) {
  7. String id = node.get(&quot;id&quot;).asText();
  8. JsonNode children = node.get(&quot;children&quot;);
  9. List&lt;String&gt; childSubtree = new ArrayList&lt;&gt;(currentSubtree);
  10. childSubtree.add(id);
  11. subtrees.addAll(getSubtrees(children, childSubtree));
  12. }
  13. }
  14. return subtrees;
  15. }

call it as

  1. List&lt;List&lt;String&gt;&gt; subtrees = getSubtrees(children, List.of());

where children is an array node of top level children, in your case it's a arbre -&gt; children json node. That's an example, pay attention to type/null checks.

答案2

得分: 1

以下是您提供的代码的中文翻译部分:

  1. public List<List<String>> getSubtrees(JsonNode childrenNode, List<String> currentSubtree) {
  2. ArrayList<List<String>> subtrees = new ArrayList<>();
  3. if (childrenNode.size() == 0) {
  4. subtrees.add(currentSubtree);
  5. } else {
  6. for (int i = 0; i < childrenNode.size(); i++) {
  7. //System.out.println(childrenNode.get(i).toString());
  8. String id = childrenNode.get(i).get("id").toString();
  9. //System.out.println(id);
  10. JsonNode children = childrenNode.get(i).get("children");
  11. List<String> childSubtree = new ArrayList<>(currentSubtree);
  12. childSubtree.add(id);
  13. //System.out.println(childSubtree.toString());
  14. subtrees.addAll(getSubtrees(children, childSubtree));
  15. }
  16. }
  17. //System.out.println(subtrees.size());
  18. return subtrees;
  19. }
  20. public List<List<String>> preProcessGetSubtrees(String tree) throws JsonProcessingException, IOException {
  21. if (!isNullorEmpty(tree)) {
  22. List<String> currentSubtree = new ArrayList<>();
  23. ObjectMapper objMapper = new ObjectMapper();
  24. System.out.println("=========================== PLANETE TREE PROCESSING ========================");
  25. List<List<String>> subtrees = getSubtrees(objMapper.readTree(tree).get("arbre").get("children"), currentSubtree);
  26. System.out.println("=========================== PLANETE TREE PROCESSED ========================");
  27. return subtrees;
  28. } else {
  29. System.out.println("============================================================================");
  30. System.out.println("==================== WARNING THE TREE IS NOT VALID =========================");
  31. System.out.println("============================================================================");
  32. return null;
  33. }
  34. }

请注意,代码中的HTML实体编码已被还原为正常的字符。如果需要进一步的帮助,请随时提问。

英文:

With the solution in the (accpeted) answer (https://stackoverflow.com/a/76456855/14707253)

I made a few modifications but the solution in itself worked so here is the final code : Function

  1. public List&lt;List&lt;String&gt;&gt; getSubtrees(JsonNode childrenNode, List&lt;String&gt; currentSubtree) {
  2. ArrayList&lt;List&lt;String&gt;&gt; subtrees = new ArrayList&lt;&gt;();
  3. if (childrenNode.size() == 0) {
  4. subtrees.add(currentSubtree);
  5. } else {
  6. for (int i = 0; i &lt; childrenNode.size(); i++) {
  7. //System.out.println(childrenNode.get(i).toString());
  8. String id = childrenNode.get(i).get(&quot;id&quot;).toString();
  9. //System.out.println(id);
  10. JsonNode children = childrenNode.get(i).get(&quot;children&quot;);
  11. List&lt;String&gt; childSubtree = new ArrayList&lt;&gt;(currentSubtree);
  12. childSubtree.add(id);
  13. //System.out.println(childSubtree.toString());
  14. subtrees.addAll(getSubtrees(children, childSubtree));
  15. }
  16. }
  17. //System.out.println(subtrees.size());
  18. return subtrees;
  19. }

And the call of the function :

  1. public List&lt;List&lt;String&gt;&gt; preProcessGetSubtrees(String tree) throws JsonProcessingException, IOException {
  2. if(!isNullorEmpty(tree)) {
  3. List&lt;String&gt; currentSubtree = new ArrayList&lt;&gt;();
  4. ObjectMapper objMapper = new ObjectMapper();
  5. System.out.println(&quot;=========================== PLANETE TREE PROCESSING ========================&quot;);
  6. //List&lt;List&lt;String&gt;&gt; subtrees =
  7. List&lt;List&lt;String&gt;&gt; subtrees = getSubtrees(objMapper.readTree(tree).get(&quot;arbre&quot;).get(&quot;children&quot;), currentSubtree);
  8. System.out.println(&quot;=========================== PLANETE TREE PROCESSED ========================&quot;);
  9. return subtrees;
  10. } else {
  11. System.out.println(&quot;============================================================================&quot;);
  12. System.out.println(&quot;==================== WARNING THE TREE IS NOT VALID =========================&quot;);
  13. System.out.println(&quot;============================================================================&quot;);
  14. return null;
  15. }

huangapple
  • 本文由 发表于 2023年6月12日 17:54:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76455492.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定