Rachana Rachana - 4 months ago 17
JSON Question

Reading a json object with array

{
"blogURL": "http://crunchify.com",
"twitter": "http://twitter.com/Crunchify",
"social": [{
"id": "1",
"message": "hi"

},
{
"id": "2",
"message": "hello"

}]
}


I am trying to read the above .txt file using the code given below.

package com.srishti.space_om;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;



public class SPACE_Parse {
public static void main(String[] args) throws FileNotFoundException, JSONException {
String jsonData = "";
BufferedReader br = null;
try {
String line;
br = new BufferedReader(new FileReader("C:/Users/Rachana/workspace/SPACEOM/WebContent/Data/Parse_JSON.txt"));
while ((line = br.readLine()) != null) {
jsonData += line + "\n";
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
// System.out.println("File Content: \n" + jsonData);
JSONObject obj = new JSONObject(jsonData);
System.out.println("blogURL: " + obj.getString("blogURL"));
System.out.println("twitter: " + obj.getString("twitter"));

}
}


I am able to read blogURL and twitter but how can I read the first social array i.e, i must be able to read social[0][id] and get 1 and social[1][id] = 2.

Answer

smth like that:

JSONArray array = obj.getJSONArray("social");
for (int i = 0; i < array.length(); i++) {
    JSONObject row = array.getJSONObject(i);
    id = row.getInt("id");
    message= row.getString("message");
}