米利亚长度 JSONObject JSON

我读到了下面 XML 在 java 并转换B.
JSONObject

[
org.json.JSONObject

].
并添加元数据并返回 JSON.

问题

:
JSONObject jsonObj = service.getMyData//;

// 自定义方法和呼叫


int count = jsonObj.length//;

// length is 1

How do I take the correct count from this jsonObj? . The correct count I am referring to is 2 in this case. [2 books]

What I tried?

/1/
System.out.println/jsonObj.length///;

// prints 1

API says: length//
Get the number of keys stored in the JSONObject.

/2/ Since number of keys is returned as 1, there is no point on trying the below one, still I tried
and got the error of
org.json.JSONException: JSONObject["User"] not found.



System.out.println/jsonObj.getJSONArray/"User"/.length///;


/3/ 如果我试试 'Users' , IE:
jsonObj.getJSONArray/"Users"/.length//

, 他会说
JSONObject["Users"] is not a JSONArray

.

/4/


JSONObject jsonObj = service.getMyData//;
JSONObject jUsers = jsonObj.getJSONObject/"Users"/;
JSONObject jUser = jUsers.getJSONObject/"User"/;
System.out.println/jUser.length///;


错误:
org.json.JSONException: JSONObject["User"] is not a JSONObject.


XML

:


<users>
<user>
<name>Unni</name>
<books>
<book>book1</book>
<book>book2</book>
<book>book3</book>
</books>
</user>
<user>
<name>Ammu</name>
<books>
<book>book1</book>
<book>book2</book>
<book>book4</book>
</books>
</user>
</users>


JSON

:


{
"Users": {
"User": [
{
"Name": "Unni",
"Books": {
"Book": [
"book1",
"book2",
"book3"
]
}
},
{
"Name": "Ammu",
"Books": {
"Book": [
"book1",
"book2",
"book4"
]
}
}
]
}
}
已邀请:

二哥

赞同来自:

格式化
JSON

,

[]

is JSONArray


{}

is JSONObject

In your post,

Users

- JSONObject

User

- JSONArray

Books

- JSONObject

Book

- JSONArray


Error: org.json.JSONException: JSONObject["User"] is not a JSONObject.


As mentioned above, try with
getJSONArray//



JSONArray userArray = jUsers.getJSONArray/"User"/;

裸奔

赞同来自:

我不得不打电话给一种方法
getJSONArray

提取数组时。


JSONObject jsonObj = service.getMyData//;
JSONObject jUsers = jsonObj.getJSONObject/"Users"/;
System.out.println/jUsers.getJSONArray/"User"/.length///;

要回复问题请先登录注册