简体   繁体   中英

How to convert json object into java

Here is my java code to get response from server.

    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();
    }

here is what php script returns.

{ "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" 
 }
 ]
 }

how do iterate to get thus assigned to variables in java.

Since you know the structure you can simply cast the heck out of the Object s like so:

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"));
}

If you are unsure of the structure I suggest using a debugger and inspecting what's in the json variable.

If you are looking for a more generic and robust approach you will have to look at the documentation like Thomas W pointed out in one of the comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM