我想将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