package org.example;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
fastjson
public class GraphJSONReader {
public static void main(String[] args) {
String fileName = “1.json”; // 替换为你的JSON文件路径
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
StringBuilder jsonContent = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
jsonContent.append(line);
}
reader.close();
// 解析JSON数据
JSONArray jsonArray = JSON.parseArray(jsonContent.toString());
// 处理每个图定义
for (Object graphObject : jsonArray) {
JSONObject jsonObject = (JSONObject) graphObject;
String kind = jsonObject.getString("kind");
JSONArray vexs = jsonObject.getJSONArray("vexs");
System.out.println("Graph Type: " + kind);
System.out.println("Vertices: " + vexs);
if ("UDG".equals(kind)) {
JSONArray arcs = jsonObject.getJSONArray("arcs");
JSONArray weight = jsonObject.getJSONArray("weight");
List<List<String>> adjacencyList = new ArrayList<>();
List<List<String>> weightList = new ArrayList<>();
for (int i = 0; i < vexs.size(); i++) {
adjacencyList.add(new ArrayList<>());
weightList.add(new ArrayList<>());
}
int m=0;
for (Object arc : arcs) {
String arcStr = arc.toString();
arcStr = arcStr.substring(1, arcStr.length() - 1); // 去除括号
String[] endpoints = arcStr.split(",");
String v1 = endpoints[0];
String v2 = endpoints[1];
int index1 = vexs.indexOf(v1);
int index2 = vexs.indexOf(v2);
adjacencyList.get(index1).add(v2);
adjacencyList.get(index2).add(v1);
weightList.get(index1).add((String) weight.get(m));
weightList.get(index2).add((String) weight.get(m));
m++;
}
System.out.println("Adjacency List:");
for (int i = 0; i < adjacencyList.size(); i++) {
System.out.println(vexs.get(i) + " -> " + adjacencyList.get(i)+"权值"+weightList.get(i));
}
}else if ("DN".equals(kind)) {
JSONArray arcs = jsonObject.getJSONArray("arcs");
JSONArray weight = jsonObject.getJSONArray("weight");
List<List<String>> adjacencyList = new ArrayList<>();
List<List<String>> weightList = new ArrayList<>();
for (int i = 0; i < vexs.size(); i++) {
adjacencyList.add(new ArrayList<>());
weightList.add(new ArrayList<>());
}
int m=0;
for (Object arc : arcs) {
String arcStr = arc.toString();
arcStr = arcStr.substring(1, arcStr.length() - 1); // 去除括号
String[] endpoints = arcStr.split(",");
String v1 = endpoints[0];
String v2 = endpoints[1];
int index1 = vexs.indexOf(v1);
adjacencyList.get(index1).add(v2);
weightList.get(index1).add((String) weight.get(m));
m++;
}
System.out.println("Adjacency List:");
for (int i = 0; i < adjacencyList.size(); i++) {
System.out.println(vexs.get(i) + " -> " + adjacencyList.get(i)+"权值"+weightList.get(i));
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}