关于#java#的问题,如何解决?

各位,求一个java算法,根据json数据,返回树的所有路径
如下json返回 A-B-C-D和A-E
json如下:
{
"result":{

    "relations":[
        
        {
            "source":"A",
            "target":"B"
        },
        {
            "source":"B",
            "target":"C"
        },
        {
            "source":"C",
            "target":"D"
        },
        {
            "source":"A",
            "target":"E"
        }
    ]
},
"status":{
    "code":0,
    "desc":"success"
}

}

仅供参考,望采纳:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class Main {
  static class Node {
    String name;
    List<Node> children = new ArrayList<>();
  }

  static Map<String, Node> nodes = new HashMap<>();

  static void buildTree(String source, String target) {
    Node sourceNode = nodes.get(source);
    if (sourceNode == null) {
      sourceNode = new Node();
      sourceNode.name = source;
      nodes.put(source, sourceNode);
    }

    Node targetNode = nodes.get(target);
    if (targetNode == null) {
      targetNode = new Node();
      targetNode.name = target;
      nodes.put(target, targetNode);
    }

    sourceNode.children.add(targetNode);
  }

  static void getPaths(Node root, String path, List<String> paths) {
    path += root.name + "-";
    if (root.children.isEmpty()) {
      paths.add(path.substring(0, path.length() - 1));
      return;
    }

    for (Node child : root.children) {
      getPaths(child, path, paths);
    }
  }

  public static void main(String[] args) {
    // 根据JSON数据中的关系构建树
    List<Map<String, String>> relations = getRelationsFromJson();
    for (Map<String, String> relation : relations) {
      buildTree(relation.get("source"), relation.get("target"));
    }

    // 获取根节点(A)
    Node root = nodes.get("A");

    // 获取从根开始的所有路径
    List<String> paths = new ArrayList<>();
    getPaths(root, "", paths);
    System.out.println(paths);
  }
}

我现在写给你


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;

import java.util.*;

public class Test {
    @SneakyThrows
    public static void main(String[] args) {
        String data = "{\n" +
                "\"result\": {\n" +
                "  \"relations\": [\n" +
                "    " +
                "{\n" +
                "      \"source\": \"A\"" +
                ",\n" +
                "      \"target\": \"B" +
                "\"\n" +
                "    },\n" +
                "    " +
                "{\n" +
                "      \"source\": \"B\"" +
                ",\n" +
                "      \"target\": \"C" +
                "\"\n" +
                "    },\n" +
                "    " +
                "{\n" +
                "      \"source\": \"C\"" +
                ",\n" +
                "      \"target\": \"D" +
                "\"\n" +
                "    },\n" +
                "    " +
                "{\n" +
                "      \"source\": \"A\"" +
                ",\n" +
                "      \"target\": \"E" +
                "\"\n" +
                "    },\n" +
                "    " +
                "{\n" +
                "      \"source\": \"B\"" +
                ",\n" +
                "      \"target\": \"F" +
                "\"\n" +
                "    },\n" +
                "    " +
                "{\n" +
                "      \"source\": \"B\"" +
                ",\n" +
                "      \"target\": \"G" +
                "\"\n" +
                "    }\n" +
                " " +
                " " +
                "]\n" +
                "}" +
                ",\n" +
                "\"status\": " +
                "{\n" +
                "\"code\": 0" +
                ",\n" +
                "\"desc\": \"success" +
                "\"\n" +
                "}\n" +
                "}";
        final ObjectMapper objectMapper = new ObjectMapper();
        final JsonNode jsonNode = objectMapper.readTree(data);
        final JsonNode relations = jsonNode.at("/result/relations");
        final Iterator<JsonNode> iterator = relations.iterator();
        final ArrayList<JsonNode> objects = new ArrayList<>();
        while (iterator.hasNext()) {
            objects.add(iterator.next());
        }
        final ArrayList<JsonNode> end = new ArrayList<>();
        for (JsonNode item : objects) {
            boolean isEnd = true;
            for (JsonNode subItem : objects) {
                if (item == subItem) {
                    continue;
                } else if (subItem.get("source").asText().equals(item.get("target").asText())) {
                    isEnd = false;
                    break;
                }
            }
            if (isEnd) {
                end.add(item);
            }
        }
        final List<List<JsonNode>> result = new ArrayList<>();
        for (JsonNode item : end) {
            final List<JsonNode> temp = new ArrayList<>();
            temp.add(item);
            JsonNode temp1 = item;
            label1:
            while (temp1 != null) {
                for (JsonNode temp2 : objects) {
                    if (temp2.get("target").asText().equals(temp1.get("source").asText())) {
                        temp1 = temp2;
                        temp.add(temp2);
                        continue label1;
                    }
                }
                temp1 = null;
            }
            Collections.reverse(temp);
            result.add(temp);
        }
        for (List<JsonNode> item : result) {
            String temp = "";
            for (int i = 0; i < item.size(); i++) {
                temp += item.get(i).get("source").asText();
                if (i == item.size() - 1) {
                    temp += item.get(i).get("target").asText();
                }
            }
            System.out.println(temp);
        }
    }
}

参考:

import com.google.gson.Gson;
import java.util.List;
import java.util.Map;

public class Main {
  private static Map<String, Object> data;

  public static void main(String[] args) {
    // 使用Gson解析JSON数据
    Gson gson = new Gson();
    data = gson.fromJson(jsonString, Map.class);

    // 从节点A开始查找路径
    findPaths("A", new ArrayList<>());
  }

private static void findPaths(String node, List<String> path) {
  // 添加当前节点到路径
  path.add(node);
  // 寻找以当前节点为起点的边
  for (Map<String, String> relation : data.get("relations")) {
    if (relation.get("source").equals(node)) {
      // 将目标节点添加到路径并递归
      findPaths(relation.get("target"), path);
    }
  }
  // 找到一条路径后打印它
  System.out.println(path);
}

提供参考实例【java递归算法实现拼装树形JSON数据】,链接:https://www.cnblogs.com/shuilangyizu/p/7205710.html


import com.google.gson.Gson;
import java.util.List;
import java.util.Map;
public class Main {
  private static Map<String, Object> data;
  public static void main(String[] args) {
    // 使用Gson解析JSON数据
    Gson gson = new Gson();
    data = gson.fromJson(jsonString, Map.class);
    // 从节点A开始查找路径
    findPaths("A", new ArrayList<>());
  }
private static void findPaths(String node, List<String> path) {
  // 添加当前节点到路径
  path.add(node);
  // 寻找以当前节点为起点的边
  for (Map<String, String> relation : data.get("relations")) {
    if (relation.get("source").equals(node)) {
      // 将目标节点添加到路径并递归
      findPaths(relation.get("target"), path);
    }
  }
  // 找到一条路径后打印它
  System.out.println(path);
}