簡體   English   中英

從以不必要數據開頭的URL中以Java讀取JSON

[英]Read JSON in Java from URL that starts with unnecessary data

我想處理以不需要的對象開頭的JSON數據。

這里有URL:

我一直在嘗試改編下一個代碼,但是我不知道如何避免第一個對象(摘要)而采用第二個對象(資源)。

如果我要從“資源”的每個對象中一一拿走所有內部數據(例如,顯示“ 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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM