一、首先需要在Eclipse工程中导入相关的jar包,jar包参见链接:http://yunpan.alibaba-inc.com/share/link/NdA5b6IFK
二、提供一份待解析的json文件,apkinfo.json如下:
[
{
"name":"帐号",
"package_name":"com.android.account",
"check_version":"1.2"
},
{
"name":"系统升级",
"package_name":"com.android.osupdate",
"check_version":"1.0"
},
]
三、Java代码由两个类组成,一个是读取文件内容的Util类,还有一个是主程序Test类。
(1)Util.java:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class Util {
public String ReadFile(String Path){
BufferedReader reader = null;
String laststr = "";
try{
FileInputStream fileInputStream = new FileInputStream(Path);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
reader = new BufferedReader(inputStreamReader);
String tempString = null;
while((tempString = reader.readLine()) != null){
laststr += tempString;
}
reader.close();
}catch(IOException e){
e.printStackTrace();
}finally{
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return laststr;
}
}
(2)Test.java:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String JsonContext = new Util().ReadFile("D:\test\apkinfo.json");
JSONArray jsonArray = JSONArray.fromObject(JsonContext);
int size = jsonArray.size();
System.out.println("Size: " + size);
for(int i = 0; i < size; i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
System.out.println("[" + i + "]name=" + jsonObject.get("name"));
System.out.println("[" + i + "]package_name=" + jsonObject.get("package_name"));
System.out.println("[" + i + "]check_version=" + jsonObject.get("check_version"));
}
}
}
四、执行后的结果如下:
Size: 2
[0]name=帐号
[0]package_name=com.android.account
[0]check_version=1.2
[1]name=系统升级
[1]package_name=com.android.osupdate
[1]check_version=1.0