获得json内在对象的价值

时间:2014-08-15 16:27:57

标签: android json android-json

我是android编码的初学者。我正在开发一个以jSON格式从php web服务获取数据的应用程序,但我无法正确解析它。

返回的JSON看起来像这样:

{
    "posts": [
        {
            "post": {
                "Id": "1",
                "Title": "Captain America",
                "Lang": "ENG"
            }
        }
    ]
}

Android代码:

JSONObject job = new JSONObject(json);//json is the string returned by web service
jObj = job.getJSONArray("posts");

JSONObject c = jObj.getJSONObject(0);
String title = c.getString("Title");

但我得到一个JSON异常:Title

没有值

我无法弄清楚什么是错的。

2 个答案:

答案 0 :(得分:0)

你有

 {  //JSONObject job = new JSONObject(json); ok
    "posts": [  // jObj = job.getJSONArray("posts"); ok
        {        // JSONObject c = jObj.getJSONObject(0) ok 
            "post": { // forgot about jsonobject post // missed  JSONObject post = c.getJSONObject("post")
                "Id": "1",
                "Title": "Captain America",

更改为

 JSONObject c = jObj.getJSONObject(0);
 JSONObject post = c.getJSONObject("post");
 String title = post.getString("Title");

答案 1 :(得分:0)

JSONObject job = new JSONObject(json);//json is the string returned by web service
JSONArray jar=job.getJSONArray("posts");
    for (int i=0;i<jar.length();i++)
    {
        job=jar.getJSONObject(i);
        job=jat.getJSONObject("post");
        title=job.optString("Title");
    }

你忘记了“发布”值

相关问题