如何从Java中的txt文件读取JSON数据? [英] How to Read JSON data from txt file in Java?
问题描述
我现在想从本地txt文件(如下所示,NODES.txt
)中读取一系列JSON数据(节点数据).我使用javax.json来做到这一点.
I am now want to read a series of JSON data(Nodes data) from local txt file(shown below, NODES.txt
). I use javax.json to do this.
当前,我有一个 Node类,其中包含以下属性:type, id, geometry class(contains type, coordinates), properties class (contains name);
Currently, I have a Node class which contains the attributes:type, id, geometry class(contains type, coordinates), properties class (contains name);
这是我需要检索的数据,其中包含500多个节点,在这里我只列出了其中的3个节点,因此我需要使用循环来做到这一点,对此我还是很陌生的,请帮忙!
NODES.txt中的示例JSON数据
The sample JSON data in NODES.txt
[
{
"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
}
}
]
推荐答案
创建代表条目的类:
Feature.java:
Feature.java:
import java.util.Map;
public class Node {
public String type;
public String id;
public Geometry geometry;
public Properties properties;
}
Geometry.java:
Geometry.java:
import java.util.List;
public class Geometry {
public String type;
public List<Double> coordinates;
}
Properties.java:
Properties.java:
public class Properties {
public String name;
}
和一个用于驱动处理的应用程序主类.
And an application main class to drive the processing.
Main.java:
Main.java:
import com.google.gson.Gson;
import java.io.FileReader;
import java.io.Reader;
public class Main {
public static void main(String[] args) throws Exception {
try (Reader reader = new FileReader("NODES.txt")) {
Gson gson = new Gson();
Node[] features = gson.fromJson(reader, Node[].class);
// work with features
}
}
}
这篇关于如何从Java中的txt文件读取JSON数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!