我的web服务将json编码的数据返回到java应用程序。如何让java应用程序正确读取json_encoded数据?例如,返回的数据看起来像这样{“必要性”:-18,“乐趣”:26,“教育”:0.6,“给予”:0,"ffa":3.8,"ltss":909.6,“消息”:数组{“1”:33,"2":44}},你可以看到里面有一些嵌套的数据。如何让java应用程序读取返回的字符串,如下所示(如果是在php中完成的话) echo returndata"necessities“,它显示-18 echo returndata"message”,并显示33。
发布于 2011-12-19 01:34:33
在Java中,所有东西都是对象,所以您需要从这个JSON字符串构建一个对象。
您可以使用这个小型库:http://json.org/java/
这样,您就能够构建JSONObjects、JSONArrays等,并提取所需的所有信息。
下面是一个示例:
/**
* Constructs feed items based on the JSON string.
*
* @param response String containing JSON with feed items array.
* @throws JSONException
*/
public FeedItems(String response) throws JSONException
{
JSONObject json = new JSONObject(response);
JSONArray items = json.getJSONArray("items");
for (int i = 0; i < items.length(); i++)
{
JSONObject feedItemObject = items.getJSONObject(i);
String id = feedItemObject.getString("id");
String title = feedItemObject.getString("title");
FeedItem feedItem = new FeedItem(id, title);
feedItems.add(feedItem);
}
}https://stackoverflow.com/questions/8553384
复制相似问题