packagecom.zving.demo;importjava.io.File;importjava.io.FileOutputStream;importjava.io.FileReader;importjava.io.OutputStreamWriter;importcom.google.gson.JsonArray;importcom.google.gson.JsonObject;importcom.google.gson.JsonParser;public classJSONStudy {public static voidmain(String[] args) {
writeJSON();
readJSON();
}public static voidwriteJSON() {
JsonObject object= newJsonObject();
object.addProperty("Info", "学生数据");
JsonArray array= newJsonArray();
JsonObject obj1= newJsonObject();
obj1.addProperty("id", 1);
obj1.addProperty("name", "张三");
obj1.addProperty("sex", "男");
obj1.addProperty("age", 18);
array.add(obj1);
JsonObject obj2= newJsonObject();
obj2.addProperty("id", 2);
obj2.addProperty("name", "李四");
obj2.addProperty("sex", "女");
obj2.addProperty("age", 22);
array.add(obj2);
JsonObject obj3= newJsonObject();
obj3.addProperty("id", 3);
obj3.addProperty("name", "王五");
obj3.addProperty("sex", "男");
obj3.addProperty("age", 20);
array.add(obj3);
object.add("Student", array);try{
FileOutputStream fos= new FileOutputStream(new File("resource/jsonLearn.json"));
OutputStreamWriter osw= new OutputStreamWriter(fos, "utf-8");
osw.write(object.toString());
osw.flush();
osw.close();
}catch(Exception e) {
e.printStackTrace();
}
}public static voidreadJSON() {try{
JsonParser parser= newJsonParser();
JsonObject object= (JsonObject) parser.parse(new FileReader("resource/jsonLearn.json"));
String info= new String(object.get("Info").getAsString().getBytes("GBK"), "utf-8");
System.out.println("Info内容是:" +info);
JsonArray array= object.getAsJsonArray("Student").getAsJsonArray();for (int i = 0; i < array.size(); i++) {
JsonObject obj=array.get(i).getAsJsonObject();int id = obj.get("id").getAsInt();
String name= new String(obj.get("name").getAsString().getBytes("GBK"), "utf-8");
String sex= new String(obj.get("sex").getAsString().getBytes("GBK"), "utf-8");int age = obj.get("age").getAsInt();
System.out.println("第" + i + "行数据为: " + id + " " + name + " " + sex + " " +age);
}
}catch(Exception e) {
e.printStackTrace();
}
}
}