I\'m new to JSON and REST. I\'m working with a server that returns strings like these:
[{\"username\":\"Hello\",\"email\":\"hello@email.com\",\"credits\":\"1
the code sample
String json = "[{\"username\":\"Hello\",\"email\":\"hello@email.com\",\"credits\":\"100\",\"twitter_username\":\"\"},{\"username\":\"Goodbye\",\"email\":\"goodbye@email.com\",\"credits\":\"0\",\"twitter_username\":\"\"}]";
JsonArray jArray = new JsonParser().parse(json).getAsJsonArray();
for (int i=0;i<jArray.size();i++) {
JsonObject jsonObject = jArray.get(i).getAsJsonObject();
System.out.println(jsonObject.get("username"));
System.out.println(jsonObject.get("email"));
System.out.println(jsonObject.get("credits"));
System.out.println(jsonObject.get("twitter_username"));
System.out.println("*********");
}
I have used org.json.simple.JSONObject and org.json.simple.JSONArray, and I hope net.sf.json.JSONArray also work same.
You should put following string format for output (JSONArray array = new JSONArray(output); )
{"YOUR_ARRAY_NAME": [{"username":"Hello","email":"hello@email.com","credits":"100","twitter_username":""},{"username":"Goodbye","email":"goodbye@email.com","credits":"0","twitter_username":""}]}
Now this is String representation of JSONArray.
I am using gson library to manipulate json. You can download gson from here. It is a very good library to handle json. Create json parser first, it will parse the json string:
JsonParser parser = new JsonParser();
now initialize an empty json array
JsonArray jArray = new JsonArray();
Now use the parser to create json array
jArray = parser.parse(outputString).getAsJsonArray();