I have to iterate through a List of Mapper and maper is a list of strings, my json looks like:
{ "aa":{ "val":"", "agl": [ { "a": "A1", "b": "B1", "c": "C1" }, { "a": "A2", "b": "B2", "c": "C2" } ] } }
The result is to get a,b and c values with iterator mode. I tried this the code below but i have the same error JSONArray[0] is not a JSONObject
List<Mapper> agl= fileDescription.get("aa").getAgl();
JSONArray jsonArray = new JSONArray(agl);
System.out.println(jsonArray);
for (int i = 0; i < jsonArray.length(); i++) {
Object jsonObj = jsonArray.getJSONObject(i);
System.out.println(jsonObj);
}
I tried also this code but it don't give me the result i need:
Iterator iterator = agl.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
System.out.println( iterator1.getA());
Mapper.java
public class Mapper{
@JsonProperty("a")
private String a;
@JsonProperty("b")
private String b;
@JsonProperty("c")
private String c;
public String getA() {
return a;
}
public void setA(String a) {
this.a= a;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b= b;
}
public String getC() {
return c;
}
public void setC(String c) {
this.c= c;
}
@Override
public String toString() {
return "{\"a\":" + "\""+a+ "\"" + ", \"b\":" + "\"" + b + "\"" + ", \"c\":" + "\"" + c + "\"" + "}";
}
}
I think you're misusing the type system. You already have a valid list to iterate. Don't create another one
List<Mapper> agl= fileDescription.get("aa").getAgl();
Iterator<Mapper> iterator = agl.iterator();
while (iterator.hasNext()) {
Mapper m = iterator.next();
System.out.println(m.getA());
}
Or simply
List<Mapper> agl= fileDescription.get("aa").getAgl();
for (Mapper m : agl) {
System.out.println(m.getA());
}
Or agl.forEach(m -> System.out.println(m.getA()));
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.