Tuesday 30 August 2016

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

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...