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