如何从Java中的txt文件中读取JSON数据?

时间:2015-11-10 20:16:46

标签: java json

我现在想从本地txt文件中读取一系列JSON数据(节点数据)(如下所示,NODES.txt)。我使用javax.json来做到这一点。

目前,我有一个节点类,其中包含以下属性: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
   }
  }
]

2 个答案:

答案 0 :(得分:2)

首先,读入文件并将内容存储在 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...
    ....
    ....
}

答案 1 :(得分:0)

创建表示条目的类:

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<Double> coordinates;
}

Properties.java:

public class Properties {
     public String name;
}

用于驱动处理的应用程序主类。

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