我想將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");
注:請讓我知道,是否有可能我們不能在代碼中使用循環?如果是,那麼給出解決方案,對於這個給定的問題還有另一種解決方案。
謝謝。
謝謝, 沒有for循環可能嗎? –
其可能但不推薦,因爲數組總是更好地通過循環訪問。但是,您可以使用'while'循環代替'for循環,但我認爲它不會對您的情況產生任何影響。但是如果你知道你總是會得到一個數組中的一個對象,那麼你可以通過簡單地使用索引值來跳過數組。 'JSONObject jsonnode = jsonnodes.getJSONObject(0);' – waqaslam
@RahulPatel它可能,但如果我們是json中的多個元素,那麼這個for循環將被使用。和單個項目,我們可以做到這一點沒有循環 – user1089679