简体   繁体   English

Android:将JSONObject转换为JSONArray返回null

[英]Android: converting JSONObject to JSONArray returns null

My code: 我的代码:

JSONObject data = {"result":{"a":[{"artist":"Aney","number:"1"},{"artist":"Aney","number:"2"}],"b":[{"artist":"Boney","number:"3"},{"artist":"Boney","number:"4"}], ....
JSONObject obj = new JSONObject(data.toString());
JSONArray tasks = obj.optJSONArray("result");

But tasks returns null . 但是tasks返回null

I tried the below code but it did not work: 我尝试了以下代码,但没有成功:

JSONObject data = {"result":{"a":[{"artist":"Money",...
JSONArray tasks = data.optJSONArray("result");

Update : 更新:

My main code is : 我的主要代码是:

// get data from main url and reutnr array
JSONArray tasks = data.optJSONArray("result");
if(alert){
    // get data from another url and return object
    JSONObject data = {"result":{"a":[{"artist":"Money",...
    tasks = data.optJSONArray("result");
}

// now i use tasks in my code
if(tasks.length() > 0){
    ....
}

When you see "key": { ... } , that means key is a JSONObject . 当您看到"key": { ... }时,表示keyJSONObject

When you see "key": [ ... ] , that means key is a JSONArray . 当您看到"key": [ ... ]时,表示keyJSONArray

In your case, "result" is a JSONObject , so write this instead: 在您的情况下, "result"是一个JSONObject ,因此应这样编写:

JSONObject tasks = obj.optJSONObject("result");

The JSONArray (a, b) is inside the object 'result' inside of the root object so you have to navigate the hyerarchy to get it: JSONArray(a,b)位于根对象内部的对象“结果”内部,因此您必须导航层次结构才能获取它:

JSONObject obj = new JSONObject(data.toString());
JSONObject result = obj.getJSONObject("result");
JSONArray tasksA = result.optJSONArray("a");
JSONArray tasksB = result.optJSONArray("b");

Note that each 'a' and 'b' is a different JSONArray to be retrieved. 请注意,每个“ a”和“ b”都是要检索的不同的JSONArray。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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