简体   繁体   中英

For Loop to iterate over JSON objects inside an Array

How do I get and show each and every JSON's Object's value those I have inside an Array called learning

Here is how JSON Array looks like:

"learning": [
 {
  "code":"2K14 - 2",
  "os":"Windows - 2"
 },
 {
  "code":"2K15 - 2",
  "os":"Linux - 2"
 },
 {
  "code":"2K16 - 2",
  "os":"Mac - 2"
 }
]

Code

List<Learning> learning = value.getLearning();
for(Learning m : learning) {
     // I guess, here I am missing something, which is really useful
     String code = m.getCode();
     String os = m.getOs();
     viewHolder.learning.setText("Code: "+code+" OS: "+os);
}

When I execute my program, getting this:

Code: 2k16, OS: Mac - 2

Whereas I want to get something like this :

Code: 2k14 OS: Windows - 2,  Code: 2k15 OS: Linux - 2, Code: 2k16 OS: Mac - 2

Do it as, if want to show all data in single TextView :

viewHolder.learning.append("Code: "+code+" OS: "+os + ", ");

Use TextView.append instead of TextView.setText

Can you post your Retrofit interface and all the model classes related to that?

and then you will have something like this to read it.

String text = "";
List<Learning> learning = value.getLearning();
for(Learning m : learning) {
     // I guess, here I am missing something, which is really useful
     String code = m.getCode();
     String os = m.getOs();
     text = text + "Code: " + code + " OS: " + os + ", ";
}
viewHolder.learning.setText(text);
JSONArray jsonArray = jsonObj.getJSONArray("learning");

for(int i = 0; i < jsonArray.length(); i++)
{
    JSONObject obj  = jsonArray.getJSONObject(i);
    String code = obj.getString("code");
    String os = obj.getString("os");

    Log.i("MyClass", "Code -> " + code);
    Log.i("MyClass", OS -> " + os);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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