下面是我从服务器获取响应的java代码。
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
HttpPost httppost = new HttpPost("http://www.def.net/my_script.php");
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String s = EntityUtils.toString(entity);
JSONObject json = (JSONObject)new JSONParser().parse(s);
System.out.println("News title= " + json.get("news_title"));
System.out.println("Content= " + json.get("news_content"));
}
catch (Exception e)
{
e.printStackTrace();
}
以下是php脚本返回的内容。
{ "desktop_app_newsfeed":
[
{ "news_id": "132",
"news_title": "test1",
"news_content": "Lorem ipsum dolor sit amet Donec...",
"news_date": "2013-07-18 10:38:20" },
{ "news_id": "1",
"news_title": "Hello world!",
"news_content":"Lorem ipsum dolor sit amet Donec...",
"news_date": "2013-04-22 17:54:05"
}
]
}
如何在java中迭代以获得这样的变量赋值。
既然知道结构,就可以简单地抛出Object
的检查结果,比如:
JSONObject json = (JSONObject) new JSONParser().parse(jsonString);
JSONArray feed = (JSONArray) json.get("desktop_app_newsfeed");
for (Object item : feed) {
JSONObject news = (JSONObject) item;
System.out.println("News title= " + news.get("news_title"));
System.out.println("Content= " + news.get("news_content"));
}
如果您不确定结构,我建议使用调试器并检查json
变量中的内容。
如果你正在寻找一种更通用、更稳健的方法,你必须查看其中一条评论中指出的Thomas W等文档。