我想处理以不需要的对象开头的JSON数据。

这里有URL:


http://datos.santander.es/api/rest/datasets/callejero_calles.json?items=819


我一直在尝试改编下一个代码,但是我不知道如何避免第一个对象(摘要)并采用第二个对象(资源)。

如果我想从“资源”的每个对象中一一拿走所有内部数据(例如,显示“ nombre-calle”,“ tipo-via” ...)。

package leerjson;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class LeerJSON {

    public static void main(String[] args) throws ParseException {
        JSONParser parser = new JSONParser();

        try {
            URL oracle = new URL("http://datos.santander.es/api/rest/datasets/callejero_calles.json?items=819"); // URL to Parse
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));

            String inputLine;
            in.readLine();
            while ((inputLine = in.readLine()) != null) {
                JSONArray a = (JSONArray) parser.parse(inputLine);

                // Loop through each item
                for (Object o : a) {
                    JSONObject datos = (JSONObject) o;
                    System.out.println(datos);
                }
            }
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }


更新:
一旦看到Enra64的答案,我就不知道如何使用getJSONArray和getJSONObject,因为它不是方法。我已经将json-simple-1.1.1.jar包含到我的项目中,但是它不起作用。先感谢您!这是我的新代码:

URL oracle = new URL("http://datos.santander.es/api/rest/datasets/callejero_calles.json?items=819"); // URL to Parse
   URLConnection yc = oracle.openConnection();
   BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));

   String inputLine = in.readLine();

   JSONObject a = (JSONObject) parser.parse(inputLine);
   JSONArray resources = a.getJSONArray("resources");

   for (int i = 0; i < resources.length(); i++) {
        resources.getJSONObject(i);
   }

最佳答案

选择资源对象,如下所示:

JSONObject a = (JSONObject) parser.parse(inputLine);
JSONArray resources = a.getJSONArray("resources");


然后遍历它:

for (int i = 0; i < resources.length(); i++) {
  resources.getJSONObject(i);
}

10-07 19:04
查看更多