Wednesday, February 23, 2011

Simple java program to read json from text file

Hi All,
was busy some what from last couple of months. Finally started on liferay 6.0 from last couple of week.Today want to share simple program which can be used to read a text file and read json from it using apache commons library. Using apache commons library we can reduce our code to large extent. Here is the program.

import java.io.IOException;
import java.io.InputStream;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import org.apache.commons.io.IOUtils;


public class ClassloaderTest {

public static void main(String [] args) {
ClassLoader cl = ClassloaderTest.class.getClassLoader();
InputStream is = cl.getResourceAsStream("json.txt");
try {

String s = IOUtils.toString( is );
JSONObject json = (JSONObject) JSONSerializer.toJSON(s);

JSONObject searchresults = json.getJSONObject("searchresults");
System.out.println("ssssssss" + searchresults.optString("count", ""));
JSONArray jarray = searchresults.getJSONArray("URI");
for(int i=0 ; i < jarray.size(); i++) {
System.out.println("jarray [" + i + "] --------" + jarray.getString(i));
}
} catch(IOException e) {
e.printStackTrace();
}
}



}

and content of json.txt is below
{
"searchresults": {
"URI": ["qa1", "qa2", "qa3", "qa4", "qa5"],
"count": "5"
}
}

jason.txt you can keep in the same package where your class is.
Hope this post helps others.
Kamal

4 comments:

Manasa's Learning said...

Hi,

I have tried reding json object i got NullPointerException,

Can you please help me..

Manasa's Learning said...

Hi,
I tried reading json object,
I got NullPointerException.

Can you please help to me.

Unknown said...

@manasa: This exception you are getting because you are not able to read file.

andry said...

json is a very interesting language to be used. very good tutorial and can hopefully help me in building json in the application that I created for this lecture. thank you