2014年8月27日星期三

A Handy Method of Accessing json Data in Java

It is possible that json data is needed to be processed in Java projects. Here we'll introduce a handy method of accessing data of json files through an example. Ajson file, test.json, contains information of class, serial numbers, names, subjects and scores,etc. In this example, data will be imported, sorted by scores in descending order and written to the file test_result.json. The format of test.json is as follows:
[
    {
        "class": "Class one",
        "id": 7,
        "name": "Nicholas",
        "subject": "PE",
        "score": 60
    },
{
        "class": "Class one",
        "id": 1,
        "name": "Emily",
        "subject": "English",
        "score": 84
},
    ......

    {
        "class": "Class one",
        "id": 1,
        "name": "Emily",
        "subject": "Math",
        "score": 77
}
]

The open source project json-lib is needed to be imported into Java. To do this, the necessary packages include:
json-lib-2.4-jdk15.jar
ezmorph-1.0.6.jar
commons-lang.jar
commons-beanutils.jar
commons-logging.jar
commons-collections.jar

With the json-lib available, way of coding will be like this:
1.Import data from the file, parse them into jsonArr, the json object, using json-lib's JSONArray. 

2.Sort the values of “score” of jObject, representing all members of jsonArr object, in descending order using comparison sort algorithm. 

3.Write the sorted jsonArr to the file. 

The code is as follows: 
public static void myJson() throws Exception{
//then import data from the file
File file = new File("D:/file/test.json"); 
FileInputStreamfis = null; 
fis = new FileInputStream(file); 
InputStreamReader input = new InputStreamReader(fis); 
BufferedReader reader = new BufferedReader(input); 
String laststr = ""; 
   String tempString = null;
while ((tempString = reader.readLine()) != null) {
laststr = laststr+ tempString;
   }
reader.close();
   //then parse the imported data into json object
JSONArrayjsonArr = JSONArray.fromObject(laststr ); 
   //then sort the json data (in descending order)
JSONObjectjObject = null;
for(inti = 0;i<jsonArr.size();i++){
long l = Long.parseLong(jsonArr.getJSONObject(i).get("score").toString());
for(int j = i+1; j<jsonArr.size();j++){
longnl = Long.parseLong(jsonArr.getJSONObject(j).get("score").toString());
if(l<nl){
jObject = jsonArr.getJSONObject(j);
jsonArr.set(j, jsonArr.getJSONObject(i));
jsonArr.set(i, jObject);
}
}
}
//then write the result to the file
FileOutputStream out = new FileOutputStream("D:/file/test_result.json"); 
out.write(jsonArr.toString().getBytes()); 
out.close(); 
}

my Json function has been able to access and sort json data, but it lacks some universality. When sorting in ascending order or by several fields is required, program has to be modified. But if we want to make the function perform more universal and flexible sorting as SQL does, analysis of dynamic expressions will be required, which will result in quite complicated code. 

esProc can help Java with accessing and processing json data. It has the advantage of creating dynamic sorting expressions using simple code. It can deal with tasks about json data, like importing, accessing, computing and writing to the file, conveniently. In order to perform dynamic sorting, a sorting expression can be transferred to esProc as a parameter as follows: 


The value of parameter sortBy is score:-1. Only 5 lines of code are needed to develop a program of sorting json data in esProc. Please see below: 

A1Use read() to load data from the json file in the format of strings. (esProc's developing tool can display the computed result visually, as shown in the left part of the above figure).
A2Parse json data into a table sequence using the import@j() method.
A3Sort the data; then esProc will first compute the parameter sortBy in macro ${sortBy}. After that, the statement to be executed is A2.sort(score:-1), meaning sorting by score in descending order.
A4Parse the sorting result into strings of json format.
A5Output the stings to the file.

If the fields for and way of sorting are changed, what we need is to modify parameter sortBy instead of the program. For instance, sort by id in descending order and by score in ascending order. We may just modify sortBy into id:-1,score:1. The statement of sorting we finally execute is A2.sort(id:-1,score:1), and the result is as follows: 
This piece of esProc code can be called conveniently in Java using jdbc provided by esProc. To save the above esProc program as test.dfx file, Java will call the following code:
//create a connection between esProc and jdbc
Class.forName("com.esproc.jdbc.InternalDriver");
con= DriverManager.getConnection("jdbc:esproc:local://");
//call esProc program (the stored procedure), in which test is the file name of dfx
com.esproc.jdbc.InternalCStatementst;
st =(com.esproc.jdbc.InternalCStatement)con.prepareCall("call test(?)");
// set parameters
st.setObject(1,"id:-1,score:1");//esProc’s input parameters
// execute the esProc stored procedure
st.execute();

Here the relatively simple esProc code can be called directly in Java, so it is unnecessary to write esProc script file (like the above-mentioned test.dfx). See the following for detailed code:
st=(com. esproc.jdbc.InternalCStatement)con.createStatement();
st.executeQuery(">file(\"d:/file/test_result.json\").write(export@j(file(\"d:/file/test.json\").read().import@j().sort(score:-1)))");

The above Java code calls directly a line of esProc code, that is, import data from the text file, sort them according to specified fields and write the result to the file.

没有评论:

发表评论