JSON 文件操作

来源:互联网 发布:淘宝设置自动回复内容 编辑:程序博客网 时间:2024/06/05 06:19

一、

我的jar包集(2017):http://pan.baidu.com/s/1c1BigBA

commons-beanutils-*
commons-lang-*
commons-collections-*
commons-logging-*
ezmorph-*
json-lib-*

二、提供一份待解析的json文件,test.json(json集合,非集合json文件可以简化)如下:
我的json问件是放在web项目src下的,路径可以根据自己需要更改
[
{
"username":"root",
"truename":"roott",
"password":"paswd"
},
{
"username":"小丽",
"truename":"小毅",
"password":"小英"
},
]
三、Java代码由两个类组成,一个是读取文件内容的Util类,还有一个是主程序Test类
如果只有一个json{"":""}这种格式,只需要JSONObject jsonObject = jsonArray.getJSONObject(i);就可以了,不需要jsonArray和循环


import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

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

public class Util {

public String ReadFile(String Path) {
BufferedReader reader = null;
String JsonContext = "";
try {
FileInputStream fis = new FileInputStream(Path);
InputStreamReader inputStreamReader = new InputStreamReader(fis, "UTF-8");
reader = new BufferedReader(inputStreamReader);
String temp = null;
while ((temp = reader.readLine()) != null) {
JsonContext += temp;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return JsonContext;
}

public static void main(String[] args) {
String path = System.getProperty("user.dir") + "/src/config/test.json";
String JsonContext = new Util().ReadFile(path);
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(jsonObject);
System.out.println("jsonArray[" + i + "]:username=" + jsonObject.get("username"));
System.out.println("jsonArray[" + i + "]:truename=" + jsonObject.get("truename"));
System.out.println("jsonArray[" + i + "]:password=" + jsonObject.get("password"));
}
}
执行后的结果如下:
jsonArray.Size(): 2
{"username":"root","truename":"roott","password":"paswd"}
jsonArray[0]:username=root
jsonArray[0]:truename=roott
jsonArray[0]:password=paswd
{"username":"小丽","truename":"小毅","password":"小英"}
jsonArray[1]:username=小丽
jsonArray[1]:truename=小毅
jsonArray[1]:password=小英