I know how to parse a json array when it has a name. But I am confused as to how it is done when the array does not have a specified name. I tried following the following example on stackoverflow.
Parsing json array with no name in android
But I did not follow what was being passed into the following line of code from the above thread.
JSONArray jsonarray = new JSONArray(json);
Plus since I am a newbie, I cannot post comments and ask the user who gave the answer. Which is why I am posting the question here. Can somebody please guide me the right direction?
ReadJson.java
import java.io.FileReader;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class ReadDiffJson {
public static void main(String[] args) throws IOException, ParseException {
JSONParser jp = new JSONParser();
Object object = jp.parse(new FileReader("file1.json"));
JSONObject jo = (JSONObject) object;
JSONArray jsonarray = new JSONArray(jo);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobj = jsonarray.getJSONObject(i);
System.out.println("ID : " + i + " = " + jsonobj.getString("id"));
System.out.println("Name : " + i + " = " + jsonobj.getString("name"));
}
}
}
file1.json
[
{
"id":1,
"name":"John",
},
{
"id":2,
"name":"Bob",
}
]