package com.zving.demo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStreamWriter;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class JSONStudy {

    public static void main(String[] args) {
        writeJSON();
        readJSON();
    }

    public static void writeJSON() {
        JsonObject object = new JsonObject();
        object.addProperty("Info", "学生数据");

        JsonArray array = new JsonArray();

        JsonObject obj1 = new JsonObject();
        obj1.addProperty("id", 1);
        obj1.addProperty("name", "张三");
        obj1.addProperty("sex", "男");
        obj1.addProperty("age", 18);
        array.add(obj1);

        JsonObject obj2 = new JsonObject();
        obj2.addProperty("id", 2);
        obj2.addProperty("name", "李四");
        obj2.addProperty("sex", "女");
        obj2.addProperty("age", 22);
        array.add(obj2);

        JsonObject obj3 = new JsonObject();
        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 void readJSON() {
        try {
            JsonParser parser = new JsonParser();
            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();
        }
    }

}

 

posted on 2018-08-02 11:27  四叶草的眼泪  阅读(313)  评论(0编辑  收藏  举报