1

I used cURL to get some twitter feeds in the form of a json file ("twitter-feed.json"). I want to convert this json file to a JSONArray object. How do I do it?

I am new to Java and json. Your suggestions are most welcome.

FileInputStream infile = new FileInputStream("input/twitter-feed.json");

// parse JSON JSONArray jsonArray = new JSONArray(string);

    // use
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonObject = jsonArray.getJSONObject(i);

        System.out.println(jsonObject.getString("id"));
        System.out.println(jsonObject.getString("text"));               
        System.out.println(jsonObject.getString("created_at"));     
    }

Thanks, PD.

3 Answers 3

1

You need to read the file first, convert it to String then feed it to the JSONArray (I am assuming that you are using the JSON-Java Project. The code below illustrates how to read the file and set it to JSONArray


// read the source file, source comes from streaming API delimited by newline
// done by curl https://stream.twitter.com/1/statuses/sample.json?delimited=newline -utwitterUsername:twitterPasswd 
// > /Projects/StackOverflow/src/so7655570/twitter.json
FileReader f = new FileReader("/Projects/StackOverflow/src/so7655570/twitter.json");
BufferedReader br = new BufferedReader(f);

ArrayList jsonObjectArray = new ArrayList();
String currentJSONString  = "";

// read the file, since I ask for newline separation, it's easier for BufferedReader
// to separate each String
while( (currentJSONString = br.readLine()) != null ) {
    // create new JSONObject
    JSONObject currentObject = new JSONObject(currentJSONString);

    // there are more than one way to do this, right now  what I am doing is adding
    // each JSONObject to an ArrayList
    jsonObjectArray.add(currentObject);
}

for (int i = 0; i < jsonObjectArray.size(); i++) {
    JSONObject jsonObject = jsonObjectArray.get(i);

    // check if it has valid ID as delete won't have one
    // sample of JSON for delete : 
    // {"delete":{"status":{"user_id_str":"50269460","id_str":"121202089660661760","id":121202089660661760,"user_id":50269460}}}

    if(jsonObject.has("id")) {
        System.out.println(jsonObject.getInt("id"));
        System.out.println(jsonObject.getString("text"));               
        System.out.println(jsonObject.getString("created_at") + "\n");    
    }
}

Steps explanation :

  • Stream API does not provide valid JSON as a whole but rather a valid one specified by the delimited field. Which is why, you can't just parse the entire result as is.
  • In order to parse the JSON, I use the delimited to use newline since BufferedReader has a method readLine that we could directly use to get each JSONObject
  • Once I get each valid JSON from each line, I create JSONObject and add it to the ArrayList
  • I then iterate each JSONObject in the ArrayList and print out the result. Note that if you want to use the result immediately and don't have the need to use it later, you can do the processing itself in while loop without storing them in the ArrayList which change the code to:

// read the source file, source comes from streaming API
// done by curl https://stream.twitter.com/1/statuses/sample.json?delimited=newline -utwitterUsername:twitterPasswd 
// > /Projects/StackOverflow/src/so7655570/twitter.json
FileReader f = new FileReader("/Projects/StackOverflow/src/so7655570/twitter.json");
BufferedReader br = new BufferedReader(f);

String currentJSONString  = "";

// read the file, since I ask for newline separation, it's easier for BufferedReader
// to separate each String
while( (currentJSONString = br.readLine()) != null ) {
    // create new JSONObject
    JSONObject currentObject = new JSONObject(currentJSONString);

    // check if it has valid ID as delete status won't have one
    if(currentObject.has("id")) {
        System.out.println(currentObject.getInt("id"));
        System.out.println(currentObject.getString("text"));               
        System.out.println(currentObject.getString("created_at") + "\n");    
    }
}
Sign up to request clarification or add additional context in comments.

12 Comments

Thanks Momo for your suggestion. I tried it and I get this error: Exception in thread "main" java.text.ParseException: "A JSONArray must start with '[' at character 1 of.." My json file starts with { and ends with }. There must be a way to convert this into an array....
That means the input is not correct. I get the JSON input via URL like twitter.com/statuses/user_timeline/109531911.json and tested it before I post the answer. Can you copy and paste some of the input from your input/twitter-feed.json? It should start with the character '['
Also, can I get the source of your twitter-feed.json? Maybe I am getting from different source than yours which has different JSON feed
If I explicitly add "[" and "]" to the start and end of my json input file, I am able to get the output nicely. The input json file has many records that begin and end with { and }. And, the argument to new JSONArray needs a "String". The error points to "JSONArray jsonArray = new JSONArray(jsonString.toString());" There must be a simple way to do this....
I saw your comment just now. I am getting my json file from cURL. On a linux terminal, I do: Mac@~ $ curl stream.twitter.com/1/statuses/sample.json?delimited=length -uttt:aaa123 > ~/twitter-feed.json. Json files got this way doesn't have a leading and trailing square brackets.
|
0

You may try Gson:

For just arrays you can use:

Gson gson = new Gson();

//(Deserialization)
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class);

To deserialize an array of objects, you can just do:

Container container = new Gson().fromJson(json, Container.class);

As shown here

Comments

0

Use ObjectMapper Class from jackson library like this :

//JSON from file to Object
Staff obj = mapper.readValue(new File("c:\\file.json"), Staff.class);

//JSON from URL to Object
Staff obj = mapper.readValue(new URL("http://mkyong.com/api/staff.json"), Staff.class);

//JSON from String to Object
Staff obj = mapper.readValue(jsonInString, Staff.class);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.