JSON Parsing for Android - nested elements?

I have used this site for years, but have never published. I'm at a standstill and hope someone can help me.

I use very similar code for Slicekick to send a data-free JSON syntax application here, but it may not seem like it understands this JSON file. I edited its JSON information to reflect the exact format I'm trying to parse to save space / time. How to parse "Results" so that I can query for "Name" and "Type"? Like his problem with Similar and Info, how to parse the Info and Results in the file below?

Here is an example JSON file edited in the exact format I use:

{ "head": { "title": "Music", "status": "200" }, "Info": [ { "Name": "Mos Def", "Type": "music", "Results": [ { "Name": "Talib Kweli", "Type": "music" }, { "Name": "Black Star", "Type": "music" }, { "Name": "Little Brother", "Type": "music" } ] }, { "Name": "Mos Def", "Type": "Vehicles", "Results": [ { "Name": "Chevy", "Type": "Car" }, { "Name": "Ford", "Type": "Car" }, { "Name": "Pontiac", "Type": "Car" } ] } ] } 

Part of my code that might be of interest:

... I am doing an httpget ... which is built into StringBuilder ... creates a JSONObject with StringBuilder results

  jArray = new JSONObject(result); 

... then returns that

Then on ...

  JSONArray Info = json.optJSONArray("Info"); System.out.println("HERE IS INFO: "); System.out.println(Info); //System.out.println("HERE IS RESULTS: "); //System.out.println(Results); 

And mostly here, where I'm at a standstill. I put printed messages to try to narrow down the problem.

Parsing "Info" allows me to search for: "Name": "Mos Def" "Type": "music" -and- "Name": "Mos Def" "Type": "Vehicles"

Replacing the search "Info" with "Results" does not give me any data. (Not found)

Any ideas?

+4
source share
3 answers

You need to call your syntax code as shown below:

 jArray = new JSONObject(result); for(int i=0;i<jArray.length();i++) { JSONArray Info = json.optJSONArray("Info"); for(int j=0;j<Info.length();j++){ { System.out.println("HERE IS INFO: "); System.out.println(Info); //System.out.println("HERE IS RESULTS: "); JSONObject obj=Info.getJSONObject(j); JSONArray results=obj.getJSONArray("Results"); for(int k=0; k<results.length(); { //Process Results } } 
+1
source

This is accurate because Results is a JSONArray inside JSONArray Info . So you should try something like this,

 JSONArray Info = json.optJSONArray("Info"); JSONArray Results = null; for (int i = 0; i < array.length(); i++) { JSONObject object = Info.getJSONObject(i); Results results = object.getJSONArray("Results"); } 
+4
source

It’s better to use GSON, it from Google and JSON parsing using its piece of cake .. !! Here is a good tutorial to start it, you will be more happy with GSON.

GSON tutorial link

0
source

Source: https://habr.com/ru/post/1389601/


All Articles