【问题标题】:getting ' JSON EXCEPTION: no value for ' error?得到 ' JSON EXCEPTION: no value for ' 错误?
【发布时间】:2013-09-16 15:32:29
【问题描述】:

我正在尝试解析一个 json 数组“itemList”:

 {
    "itemsCount": "1309",
    "itemList": [
        { name: "xxx",
          id: "01"
        },
        { name: "yyy",
          id: "02"
        }
      ]
    }

但我得到“ json exception:no value for” 当我使用以下代码时。

 String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET", params);
Log.d("Albums JSON: ", "> " + json);                    
try {   
     jsonObject = new JSONObject().getJSONObject("itemList");
     albums = jsonObject.getJSONArray("itemList"); 
         if (albums != null) {

    for (int i = 0; i < albums.length(); i++) {
    JSONObject c = albums.getJSONObject(i);

    String id = c.getString(TAG_ID);
    String name = c.getString(TAG_NAME);


    HashMap<String, String> map = new HashMap<String, String>();

    map.put(TAG_ID, id);
        map.put(TAG_NAME, name);


    albumsList.add(map);
                }
            }else{
                Log.d("Albums: ", "null");
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

在日志中我可以看到 json 值。我在以下几行中遇到错误。

jsonObject = new JSONObject().getJSONObject("itemList");
 albums = jsonObject.getJSONArray("itemList"); 

我是新手。帮我解决它。 提前致谢

【问题讨论】:

  • 您的“专辑”obj 的类型是什么?
  • itemList 是 jsonarray ,你把它当作 json 对象,所以报错,直接解析为 json 数组。
  • 在哪里设置 json 字符串作为 JSONObject 的内容?你怎么能先得到一个对象“itemList”,然后从中得到一个数组?尝试,使用 json 字符串 new JSONObject(json) 初始化 jsonObject,然后从此 josnObject.getJSONArray("itemList") 中获取数组
  • itemList 是 jsonarray ,并且您正在尝试作为 json 对象获取,因此您的行中出现错误

标签: java android json getjson


【解决方案1】:

您需要发送 json 字符串来创建 jsong 对象。

jsonObject = new JSONObject(json);
 albums = jsonObject.getJSONArray("itemList"); 

【讨论】:

  • 我试过了。但得到“json异常:value [{ itemList json values }]”
  • 知道了。这解决了我的问题“ jsonObject = new JSONObject(json); albums = jsonObject.getJSONArray("itemList"); "
【解决方案2】:

如果此任务不是教育/学术,我建议您使用 JSON 映射器。 例如 JacksonGSON。像这样“手动”解析 JSON 只是浪费时间和代码,而且更容易出错。

http://jackson.codehaus.org/

从字面上看,用映射器做同样的事情需要两行代码。

【讨论】:

    【解决方案3】:

    试试这个方法

     jsonObject = new JSONObject(json);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-10
      • 2015-05-19
      • 2015-07-10
      • 1970-01-01
      • 1970-01-01
      • 2014-03-17
      • 2021-09-12
      • 2018-05-31
      相关资源
      最近更新 更多