2013-05-13 76 views
0

我有以下格式的JSON内:如何解析JSON字符串是一个数组

{ 
    "Result": { 
     "question": "Barack Obama vs Mitt Romney?", 
     "option": [ 
      "Barack Obama", 
      "Mitt Romney", 
      "Other" 
        ], 
     "percentage": [ 
      20, 
      40, 
      80 
         ] 
       } 
} 

,我使用下面的代码来分析它,但在选择阵列此给空指针异常。

JSONParser jParser = new JSONParser();

    JSONObject json = jParser.getJSONObjectFromUrl(url); 
        Log.e("json",json.toString()); 

        Log.e("-------url-------", ""+url); 


         String resultStr = json.getString("Result"); 
         Log.e("result string ",resultStr); 

         JSONObject jsonObject2 = new JSONObject(resultStr); 


         String question_string = jsonObject2.getString("question"); 
         Log.e("question String ",question_string); 


         String option_str = jsonObject2.getString("option"); 

         JSONArray optionArray = new JSONArray(option_str); 
         Log.d("option array", String.valueOf(optionArray.length())); 
+0

这里是你的家庭作业:Android的 - JSON解析示例](HTTP ://stackoverflow.com/search?q = Android + json +解析+例子) – 2013-05-13 06:56:53

回答

0

用途:

JSONArray optionArray = jsonObject2.getJSONArray("option"); 

"option"关键点指向数组而不是String。

0

你在这里的方式太复杂了,没有使用那些可爱的GetJSONObject和getJSONArray函数,这会使你加倍解析。试试这个

   JSONParser jParser = new JSONParser(); 

       JSONObject json = jParser.getJSONObjectFromUrl(url); 
       Log.e("json",json.toString()); 

       Log.e("-------url-------", ""+url); 

        JSONObject jsonObject2 = json.getJSONObject("Result"); 


        String question_string = jsonObject2.getString("question"); 
        Log.e("question String ",question_string); 

        JSONArray optionArray = jsonObject2.getJSONArray("option"); 
+0

'new JSONObject(“Result”)'你确定吗? – Supericy 2013-05-13 06:54:14

+0

没有。这就是我从复制和粘贴他的代码并编辑而不是从头开始写的东西。谢谢你的收获。 – 2013-05-13 06:56:39

0

而不是使用

String option_str = jsonObject2.getString("option"); 

使用这样的:

JSONARRAY optionArray = jsonObject2.getJSONAray("option"); 
for(int i=0;i<optionArray.length; i++){ 
    String option = optionArray[i].getString();} 

试试这个..