Długość tablicy JSONObject JSON


Przeczytałem poniżej XML w Javie i przekonwertuj na JSonObject [ Org.json.jsonobject ].
i dodaj metadane i wróć jako JSON.

Problem
: Jsonobject Jsonobj = Service.GetMyData ();// Metody niestandardowe i wyzwania
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) Jeśli spróbuję „Użytkownicy”, czyli:
jsonObj.getJSONArray („Users”). Length ()
, mówi, że
JSONObject [„Users”] nie jest JSONArray . 
(4)
JSONObject jsonObj = service.getMyData();
JSONObject jUsers = jsonObj.getJSONObject("Users");
JSONObject jUser = jUsers.getJSONObject("User");
System.out.println(jUser.length());

Błąd:
org.json.JSONException: JSONObject ["User"] nie jest 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"
]
}
}
]
}
}

Zaproszony:
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

W formacie
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");
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

Musiałem wywołać metodę
GetJsonarray
podczas ekstrakcji tablicy.
JSONObject jsonObj = service.getMyData();
JSONObject jUsers = jsonObj.getJSONObject("Users");
System.out.println(jUsers.getJSONArray("User").length());

Aby odpowiedzieć na pytania, Zaloguj się lub Zarejestruj się