1. 程式人生 > >使用Gson實現物件或集合與json字串的互相轉化

使用Gson實現物件或集合與json字串的互相轉化

public class JsonTest {
    private static Gson gson = new Gson();

    public static Student jsonToObject(String jsonStr) {
        return gson.fromJson(jsonStr, Student.class);
    }

    public static List<Student> jsonToList(String jsonStr) {
        return gson.fromJson(jsonStr, new TypeToken<List<Student>>(){}.getType());
    }

    public String objectOrListToJson(Object object) {
        return gson.toJson(object);
    }


    public static void main(String[] args) {
        String jsonStr = "{\"id\":\"1\",\"name\":\"ji\",\"score\":\"100\"}";
        System.out.println(jsonToObject(jsonStr));

        String json = "[{\"id\":\"1\",\"name\":\"ji\",\"score\":\"100\"},{\"id\":\"2\",\"name\":\"liu\",\"score\":\"99\"}]";
        System.out.println(jsonToList(json));

        Student student = new Student(3, "liu", 100);
        System.out.println(gson.toJson(student));

        List<Student> students = new ArrayList<>();
        students.add(new Student(4, "ying", 99));
        students.add(new Student(5, "bing", 98));
        System.out.println(gson.toJson(students));
    }

    static class Student {
        int id;
        String name;
        int score;

        public Student(int id, String name, int score) {
            this.id = id;
            this.name = name;
            this.score = score;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getScore() {
            return score;
        }

        public void setScore(int score) {
            this.score = score;
        }

        @Override
        public String toString() {
            return "Student{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", score=" + score +
                    '}';
        }
    }
}