一、将数据保存为JSON格式
//将数据用JSON写入文本
public void jsonwrite() {
// 创建一组姓名数据
String[] nameArr = new String[] { "小李", "萧晨", "小张", "小王" };
// 创建一组年龄数据
int[] ageArr = new int[] { 23, 24, 22, 25 };
// 最外层json对象
JSONObject jsonObject = new JSONObject();
// json数组对象
JSONArray jsonArray = new JSONArray();
// 内层json对象
JSONObject innerJsonObject = null;
for (int i = 0; i < nameArr.length; i++) {
innerJsonObject = new JSONObject();//实例化内层对象
try {
innerJsonObject.put("姓名", nameArr[i]);
innerJsonObject.put("年龄", ageArr[i]);
jsonArray.put(innerJsonObject);//将内层对象放进jsonArray中
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
jsonObject.put("info", jsonArray);//将数组对象放进Json对象中
} catch (JSONException e) {
e.printStackTrace();
}
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "sd" + File.separator + "json.txt");//设置JSON文件存储路径
try {
PrintStream printStream = new PrintStream(
new FileOutputStream(file));
printStream.print(jsonObject);//将JSON存储到文件
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
二、用JSONObject来解析JSON文件
//解析JSON文件
public void jsonParse(){
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "sd" + File.separator + "json.txt");//解析的XML文件
try {
String jsonInfo="";
Scanner scanner=new Scanner(new FileInputStream(file));//读取输入流
while(scanner.hasNext()){
jsonInfo+=scanner.next();
}
try {
JSONObject jsonObject=new JSONObject(jsonInfo);//创建JSON对象
JSONArray jsonArray=jsonObject.getJSONArray("info");//获得名称为info的对象
//System.out.println(jsonArray.length());
for(int i=0;i<jsonArray.length();i++){//遍历数组对象中所有的对象元素
String name=jsonArray.getJSONObject(i).getString("姓名");
int age=jsonArray.getJSONObject(i).getInt("年龄");
System.out.println(name+","+age);
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
三、通过JSONReader来解析JSON文件
//解析JSON通过JSONReader
public void jsonReader(){
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "sd" + File.separator + "json.txt");//获取解析文件的路径
try {
JsonReader jsonReader=new JsonReader(new InputStreamReader(new FileInputStream(file)));
//获得JSONReader的对象
jsonReader.beginObject();//打开json读取对象
while(jsonReader.hasNext()){
String name=jsonReader.nextName();//获得对象名称
if(name.equals("info")){
jsonReader.beginArray();//打开json读取数组
while(jsonReader.hasNext()){
jsonReader.beginObject();//打开json读取对象
while(jsonReader.hasNext()){
String obName=jsonReader.nextName();
if(obName.equals("姓名2")){
System.out.println(jsonReader.nextString());
}else if(obName.equals("年龄")){
System.out.println(jsonReader.nextInt());
}
else if(obName.equals("姓名")){
System.out.println(jsonReader.nextString());
}
}
jsonReader.endObject();
}
jsonReader.endArray();
}
}
jsonReader.endObject();
} catch (Exception e) {
e.printStackTrace();
}
}