2013-03-22 134 views
0

嗨我想從ReST API讀取JSON,但我得到一個空指針異常,因爲mycode不正確。如何獲取特定的JSON數據?

我有一個JSON,我從這樣看閱讀:

processJSON({ 
"LocationList":{ 
    "noNamespaceSchemaLocation":"http://api.vasttrafik.se/v1/hafasRestLocation.xsd", 
    "servertime":"16:13", 
    "serverdate":"2013-03-22", 
    "StopLocation":[{ 
    "name":"Brunnsparken, Göteborg", 
    "lon":"11.967824", 
    "lat":"57.706944", 
    "id":"9021014001760000", 
    "idx":"1" 
    },{ 
    "name":"Brunnsgatan, Göteborg", 
    "lon":"11.959455", 
    "lat":"57.693766", 
    "id":"9021014001745000", 
    "idx":"4" 
    },{ 
    "name":"Brunnslyckan, Lerum", 
    "lon":"12.410219", 
    "lat":"57.812073", 
    "id":"9021014017260000", 
    "idx":"5" 
    }, 

現在我這取決於用戶輸入想要的名字從JSON文件。

我該如何做到這一點與代碼?

我的代碼,錯誤的是這樣的:

import org.json.simple.JSONObject; 
import org.json.simple.JSONValue; 

    public class JSONReader { 

     private String jsonData = ""; 


     public String getJsonData(String location){ 


      try { 

        URL url = new  URL("http://api.vasttrafik.se/bin/rest.exe/v1/location.name?authKey=secret&format=json&jsonpCallback=processJSON&input=" + URLEncoder.encode(location, "UTF-8")); 
        URLConnection connection = url.openConnection(); 
        BufferedReader readJsonFile = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); 
        String temp = ""; 
        while((temp = readJsonFile.readLine()) != null){ 
          jsonData += temp; 
        } 
        readJsonFile.close(); 

        System.out.println(jsonData); 
        return jsonData; 

      } 

      catch (IOException e) { 

      } 
      return null; 
    } 

     public void JSONParsing(){ 

       String location = Planner.getPlanner().getStartingLocation(); 
       JSONObject obj =(JSONObject)JSONValue.parse(getJsonData(location)); 

       //Set the text into the JList 

       if (obj.containsValue(location)); 
       obj.get("name"); 
       } 
    } 

我想從JSON獲得位置的同名出的用戶輸入。 如何使用代碼執行此操作?

+0

_I想要從用戶輸入中獲取與JSON相同的位置名稱_ < - 這是什麼意思? – 2013-03-22 15:52:16

+0

如果用戶選擇一個位置,它應該從JSON文件中找到該位置 – Josef 2013-03-22 16:35:21

回答

0

我認爲你是問如何解析您的JSONObject,並獲得相應的值了它的用戶有興趣,下面是創建一個Map,其關鍵是你如何拉開JSONObject爲例String id(因爲名稱看起來不是唯一的),其值是整個JSONObject。您可以使用該地圖來查找來自用戶的輸入,並找到合適的LLA如果這就是你所感興趣的東西。

public Map<String, JSONObject> createLocationMap(JSONObject jsonObj){ 
    Map<String, JSONObject> nameToLocationMap = new HashMap<String, JSONObject>(); 
    JSONObject locationList = (JSONObject) jsonObj.get("LocationList"); 
    JSONArray array = (JSONArray) locationList.get("StopLocation"); 
    for (int i = 0; i < array.length(); i++) { 
     String name = (String) ((JSONObject) array.get(i)).get("id"); 
     nameToLocationMap.put(name, ((JSONObject)array.get(i))); 
    } 
    return nameToLocationMap; 
} 

,你認爲合適,您可以定製此方法。例如,如果您對idname之間的關係感興趣,那麼您可以創建一個類似的方法,使用這些值而不是id和整個JSONObject'。我希望這有助於〜