gpt4 book ai didi

java - 如何用Java从txt文件中读取JSON数据?

转载 作者:行者123 更新时间:2023-12-01 22:00:20 24 4
gpt4 key购买 nike

我现在想从本地txt文件读取一系列JSON数据(节点数据)(如下所示, NODES.txt )。我使用 javax.json 来执行此操作。

目前,我有一个 Node 类,其中包含属性:type, id, geometry class(contains type, coordinates), properties class (contains name);

这是我需要检索的数据,它包含超过 500 个节点,这里我只列出其中 3 个,所以我需要使用循环来完成它,我对此很陌生,请帮忙!!

NODES.txt 中的示例 JSON 数据

[
{
"type" : "Feature",
"id" : 8005583,
"geometry" : {
"type" : "Point",
"coordinates" : [
-123.2288,
48.7578
]
},
"properties" : {
"name" : 1
}
},
{
"type" : "Feature",
"id" : 8005612,
"geometry" : {
"type" : "Point",
"coordinates" : [
-123.2271,
48.7471
]
},
"properties" : {
"name" : 2
}
},
{
"type" : "Feature",
"id" : 8004171,
"geometry" : {
"type" : "Point",
"coordinates" : [
-123.266,
48.7563
]
},
"properties" : {
"name" : 3
}
},
****A Lot In the Between****
{
"type" : "Feature",
"id" : 8004172,
"geometry" : {
"type" : "Point",
"coordinates" : [
-113.226,
45.7563
]
},
"properties" : {
"name" : 526
}
}
]

最佳答案

首先读入文件并将内容存储在ONE String中:

BufferedReader reader = new BufferedReader(new FileReader("NODES.txt"));
String json = "";
try {
StringBuilder sb = new StringBuilder();
String line = reader.readLine();

while (line != null) {
sb.append(line);
sb.append("\n");
line = reader.readLine();
}
json = sb.toString();
} finally {
reader.close();
}

然后从String中解析Json数据:

JSONObject object = new JSONObject(json); // this will get you the entire JSON node
JSONArray array = object.getJSONArray("Node"); // put in whatever your JSON data name here, this will get you an array of all the nodes

ArrayList<Node> nodeList = new ArrayList(array.length())<Node>;
for(int i=0; i<array.length(); i++){ // loop through the nodes
JSONObject temp = array.getJSONObject(i);
nodeList.get(i).setType(temp.getString("type")); //start setting the values for your node...
....
....
}

关于java - 如何用Java从txt文件中读取JSON数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33638765/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com