0
{
    "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.

1
  • There's most probably a JSONArray class that handles the arrays. In your case you'd have an array of JSONObject so you'd then do like ((JSONArray)obj.get("social")).get(0).get("id") (assuming JSONArray exists and extends JSONObject). Commented Jul 11, 2016 at 11:40

1 Answer 1

0

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");
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.