java json gbk_JAVA操作Json

该博客展示了如何使用Java的Gson库创建和读取GBK编码的JSON文件。主要内容包括创建JSON对象和数组,将数据写入JSON文件,并使用GBK解码读取JSON文件中的字符串属性。
摘要由CSDN通过智能技术生成

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();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值