php - How to convert json object into java -


here java code response 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 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 iterate assigned variables in java.

since know structure can cast heck out of objects so:

jsonobject json = (jsonobject) new jsonparser().parse(jsonstring); jsonarray feed = (jsonarray) json.get("desktop_app_newsfeed");  (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 unsure of structure suggest using debugger , inspecting what's in json variable.

if looking more generic , robust approach have @ documentation thomas w pointed out in 1 of comments.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -