2015-11-08 44 views
1

我想解析來自Web of Trust API的響應JSON。問題是API返回的JSON使用整數作爲標識符,我很難得到我想要的值。我使用org.json:json如何從JSON數組中獲取使用數字作爲標識符的值?

下面有什麼樣的JSON看起來像一個例子:

{ 
    "google.com": { 
     "target": "google.com", 
     "0": [ 94, 73 ], 
     "1": [ 94, 73 ], 
     "2": [ 94, 73 ], 
     "4": [ 93, 66 ], 
     "categories": { 
      "501": 99, 
      "301": 43 
     } 
    } 
} 

我試圖從「0」和「4」獲得的值。

繼承人我使用Java代碼解析它:

package eclipseurlplugin.handlers; 


import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.Reader; 
import java.net.URL; 
import java.nio.charset.Charset; 

import org.json.JSONException; 
import org.json.JSONObject; 


public class JsonTest { 

    private static String readAll(Reader rd) throws IOException { 
     StringBuilder sb = new StringBuilder(); 
     int cp; 
     while ((cp = rd.read()) != -1) { 
      sb.append((char) cp); 
     } 
     return sb.toString(); 
     } 

     public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException { 
     InputStream is = new URL(url).openStream(); 
     try { 
      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); 
      String jsonText = readAll(rd); 
      JSONObject json = new JSONObject(jsonText); 
      return json; 
     } finally { 
      is.close(); 
     } 
     } 

     public static void main(String[] args) throws IOException, JSONException { 

     JSONObject json = readJsonFromUrl("http://api.mywot.com/0.4/public_link_json2?hosts=google.com/&key="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); 
     String jsonValue = json.getJSONObject("google.com").getString("0"); 
     System.out.println(jsonValue);  
     } 
} 

我嘗試使用下面的代碼來獲取值,但我得到一個異常。是否有捷徑可尋?

String jsonValue = json.getJSONObject("google.com").getString("0"); 

謝謝。

+1

是什麼,你得到的異常? –

+0

那些不是整數,它們是包含數字的字符串。 –

+0

**安迪所說的** - ***總是***在詢問有關例外情況時包括您得到的例外的全文。 –

回答

-1

IN {"0": [1, 2]} 0 indentifier有整型數組所以只得到像下面JSON數組:

JSONArray msg = (JSONArray) json.getJSONObject("google.com").getJSONArray("0"); 
+0

您不能將'java.lang.String'強制轉換爲'org.json.JSONArray'。 –

+0

哦..對不起jsonObject.getJSONArray(「0」)@Andy Turner – developerbhuwan

+0

這工作完美。謝謝! – IHZachR

0

這是因爲您試圖以String的形式訪問列表。所以:

jsonObj.getString("0") 

將爲

{"0": "94, 73"} 

但不工作了

{"0": [94, 73]} 

你需要使用jsonObj.getJSONObject("0")獲得該列表。

相關問題