JSon文件解析

#json.txt

 {

name:"中国",
provinces:[
{name:"黑龙江",
citys:["佳木斯","大庆","哈尔滨","齐齐哈尔","牡丹江"]
},
{name:"辽宁",
citys:["沈阳","大连","盘锦"]
},
{name:"吉林",
citys:["吉林市","长春市","四平市"]
}
]
}
#JSonParser .java
import java.io.*;
import java.text.ParseException;
 
import org.json.*;
 
/**
 * 从json文件读取数据,形成JSon对象,读取对象数据并打印
 */
public class JSonParser {
 
public static void main(String[] args) {
//从JSon文件读取数据
StringBuffer stringBuffer = new StringBuffer();
String line = null ;
try {
BufferedReader br = new BufferedReader(new FileReader(new File("json.txt")));
while( (line = br.readLine())!= null ){
stringBuffer.append(line);
} catch (FileNotFoundException e) {
       e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
//将Json文件数据形成JSONObject对象
JSONObject jsonObject = new JSONObject(stringBuffer.toString());
//获取JSONObject对象数据并打印
JSONArray provinces = jsonObject.getJSONArray("provinces") ;
String name = null ;
StringBuffer jsonFileInfo = new StringBuffer();
JSONArray citys = null ;
for (int i = 0; i < provinces.length(); i++) {
name = provinces.getJSONObject(i).getString("name");
jsonFileInfo.append("/nname:" + name + "/n" + "citys:");
citys = provinces.getJSONObject(i).getJSONArray("citys");
for (int j = 0; j < citys.length(); j++) {
jsonFileInfo.append(citys.getString(j)+"/t");
}
}
 
System.out.println(jsonFileInfo);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
 
运行结果:
 
name:黑龙江
citys:佳木斯 大庆 哈尔滨 齐齐哈尔 牡丹江
name:辽宁
citys:沈阳 大连 盘锦
name:吉林
citys:吉林市 长春市 四平市

你可能感兴趣的:(json)