I have Json like:
{"created_at":"2014","name":"solicitice"}
{"created_at":"2015","name":"hior"}
.....
I am trying below code to get values of all variables: ....
JSONObject jsonObj = new JSONObject(sb.toString());
for (int i = 0; i < jsonObj.length(); i++) {
System.out.println(jsonObj.get("created_at"));
}
but it is printing only few lines of same value . Also ArrayList is not effective in this case.
4 Answers 4
If your input as a string is:
"{\"created_at\":\"2014\",\"name\":\"solicitice\"}\n{\"created_at\":\"2015\",\"name\":\"hior\"}"
and it is guaranteed that there is exactly one object per line, you can use a StringReader combined with a BufferedReader to read those objects and then read their values. For example like this:
String input = "...";
try (StringReader sr = new StringReader(input); BufferedReader in = new BufferedReader(sr)) {
String line;
while ((line = in.readLine()) != null) {
JSONObject object = new JSONObject(line);
System.out.println(object.get("created_at"));
}
} catch (IOException e) {
// this should not happen but let's log it anyway
e.printStackTrace();
}
This will read every line in input, transform it into a JSONObject and print its created_at field to the standard output.
Comments
Because you should define it as json array, not json object. Try:
JSONArray jsonArr = new JSONArray(sb.toString());
for (int i = 0; i < jsonArr.length(); i++) {
System.out.println(jsonArr.get(i).get("created_at"));
}
3 Comments
[, followed by an arbitrary amount of values separated by comma , and a closing bracket ].Few Corrections,
1.) Json String is not correct, should be in form of array
2.) Use JsonArray to pass, then loop, get JsonObject, then get values through keys.
public static void main(String[] args) throws JSONException {
String s = "[{\"created_at\":\"2014\",\"name\":\"solicitice\"},{\"created_at\":\"2015\",\"name\":\"hior\"}]";
JSONArray jsonArr = new JSONArray(s);
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = (JSONObject) jsonArr.get(i);
System.out.println(jsonObj.get("created_at"));
}
}
output
2014
2015
Comments
StringBuffer jsonStr = new StringBuffer("[{\"created_at\":\"2014\",\"name\":\"solicitice\"},{\"created_at\":\"2015\",\"name\":\"hior\"}]");
JsonParser jsonParser = new JsonParser();
JsonArray jsonArray = new JsonArray();
jsonArray = jsonParser.parse(jsonStr.toString()).getAsJsonArray();
System.out.println("JSON Array: " + jsonArray);
for(JsonElement json: jsonArray){
System.out.println("JSON ELEMENT: " + json);
System.out.println("NAME: " + json.getAsJsonObject().get("name"));
System.out.println("CREATED_AT: " + json.getAsJsonObject().get("created_at"));
}
[]and comma separated.StringReaderwrapped with aBufferedReaderin my answer.