2012-04-30 38 views
2

我想將JSON轉換爲java代碼。我的jsoncode如下所示。如何編寫json的java代碼

{ 
"nodes": [ 
    { 
     "node": { 
      "Name": "rahul Patel", 
      "Address": "\n\tAhmedabad", 
      "Date of Birth": "1991-05-03", 
      "Occupation": "developer", 
      "Member Since": "3 weeks 4 days" 
     } 
    } 
] 

Java代碼

try { 
      JSONObject objResponse = new JSONObject(strResponse); 

      JSONArray jsonnodes = objResponse 
        .getJSONArray(nodes); 


      System.out.println("=hello this is DoinBackground"); 
      for (i = 0; i < jsonnodes.length(); i++) { 

       System.out.println("hello this is for loop of DoinBackground"); 
       JSONObject jsonnode = jsonnodes.getJSONObject(i); 

       JSONObject jsonnodevalue = jsonnode 
         .getJSONObject(node); 

       bean = new UserProfileBean(); 

       bean.name = jsonnodevalue.getString(Name); 


       listActivities.add(bean); 

      } 
     } catch (JSONException e) { 

      e.printStackTrace(); 
     } 
} 

在這裏,我logcat中打印的價值之前,循環System.out.println("=hello this is DoinBackground");,但值不能在打印的for循環System.out.println("hello this is for loop of DoinBackground");

注:請讓我知道,是否有可能我們不能在代碼中使用循環?如果是,那麼給出解決方案,對於這個給定的問題還有另一種解決方案。

謝謝。

回答

1

你的json字符串是錯誤的。它必須與}一起發佈。解決這個問題,它會工作。

固定JSON字符串:

{ 
    "nodes": [ 
     { 
      "node": { 
       "Name": "rahul Patel", 
       "Address": "\n\tAhmedabad", 
       "Date of Birth": "1991-05-03", 
       "Occupation": "developer", 
       "Member Since": "3 weeks 4 days" 
      } 
     } 
    ] 
} 

示例代碼進行測試:

String j = "{\r\n" + 
     " \"nodes\": [\r\n" + 
     "  {\r\n" + 
     "   \"node\": {\r\n" + 
     "    \"Name\": \"rahul Patel\",\r\n" + 
     "    \"Address\": \"\\n\\tAhmedabad\",\r\n" + 
     "    \"Date of Birth\": \"1991-05-03\",\r\n" + 
     "    \"Occupation\": \"developer\",\r\n" + 
     "    \"Member Since\": \"3 weeks 4 days\"\r\n" + 
     "   }\r\n" + 
     "  }\r\n" + 
     " ]\r\n" + 
     "}"; 

try{ 
    JSONObject objResponse = new JSONObject(j); 

    JSONArray jsonnodes = objResponse.getJSONArray("nodes"); 

    for (int i = 0; i < jsonnodes.length(); i++) { 

     JSONObject jsonnode = jsonnodes.getJSONObject(i); 

     JSONObject jsonnodevalue = jsonnode 
       .getJSONObject("node"); 

     Log.v("name", jsonnodevalue.getString("Name")); 
     Log.v("address", jsonnodevalue.getString("Address")); 
     Log.v("occupation", jsonnodevalue.getString("Occupation")); 
    } 

} 
catch (Exception e) { 
    e.printStackTrace(); 
} 
+0

謝謝, 沒有for循環可能嗎? –

+0

其可能但不推薦,因爲數組總是更好地通過循環訪問。但是,您可以使用'while'循環代替'for循環,但我認爲它不會對您的情況產生任何影響。但是如果你知道你總是會得到一個數組中的一個對象,那麼你可以通過簡單地使用索引值來跳過數組。 'JSONObject jsonnode = jsonnodes.getJSONObject(0);' – waqaslam

+0

@RahulPatel它可能,但如果我們是json中的多個元素,那麼這個for循環將被使用。和單個項目,我們可以做到這一點沒有循環 – user1089679

1

嘗試使用Gson - http://code.google.com/p/google-gson/。會節省很多頭痛。

但是,在您的代碼中,請確保您的JSON字符串正在被正確解析。 可以肯定的objResponse.getJSONArray(nodes)應該是objResponse.getJSONArray("nodes")

+0

謝謝, 請讓我知道在logcat中爲什麼它不適合循環後顯示。 –