I am using org.json.simple library to construct JSONArray of JSONObject. So my structure looks like
c= [
{
"name":"test",
"age":1
},
{
"name":"test",
"age":1
}
]
To iterate the array in java, I tried
for (int i = 0; i < c.size(); i++) {
JSONObject obj = (JSONObject) c.get(i);
System.out.println(obj.get("name"));
}
It printed null, but when tried to print the obj.toString, it prints the JSON string as expected.
I am using org.json.simple jar, so cannot use the methods defined org.json.JSONArray or org.json.JSONObject.
Any ideas to get the values from the object with their key?
Your code is absolutely correct, it works fine with org.json.simple:
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonTest {
public static void main(String[] args) throws ParseException {
JSONArray c = (JSONArray) new JSONParser()
.parse("[ { \"name\":\"test\", \"age\":1 }, "
+ "{ \"name\":\"test\", \"age\":1 } ]");
for (int i = 0; i < c.size(); i++) {
JSONObject obj = (JSONObject) c.get(i);
System.out.println(obj.get("name"));
}
}
}
It outputs:
test
test
Check how input JSONArray was created. It's possible that there's something different inside it. For example, it's possible that you have non-printable character in key name, so you don't see it when using c.toString(), but obj.get("name") fails.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With