Tuesday, June 5, 2018

How to Read JSON data from txt file in Java?




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.



Currently, I have a Node class which contains the attributes:type, id, geometry class(contains type, coordinates), properties class (contains name);



Here is the data I need to retrieve, it contains more than 500 nodes in it, here I just list 3 of them, so I need to use a loop to do it, I am quite new to this, please help !!



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
}
}
]


Answer



Create classes to represent the entries:



Feature.java:



import java.util.Map;

public class Node {
public String type;

public String id;
public Geometry geometry;
public Properties properties;
}


Geometry.java:



import java.util.List;


public class Geometry {
public String type;
public List coordinates;
}


Properties.java:



public class Properties {
public String name;

}


And an application main class to drive the processing.



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
}
}
}


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...