如何将json对象转换为java

时间:2013-07-18 04:56:40

标签: java php json

这是我从服务器获取响应的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中的变量。

1 个答案:

答案 0 :(得分:0)

既然您知道结构,那么您可以简单地从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 等文档。

相关问题