GSON

What is GSON?
A Java serialization/deserialization library to convert Java Objects into JSON and back is designed by google.(Check open source GSON project)

A GSON Project
I wrote a GSON project.(Check it out)

Parse Json
How to convert a JSON into a java object? Check the following code:

File jsonFile = new File(ParseJson.class.getResource("/json/huanhuan.json").getFile());
        String content = FileUtils.readFileToString(jsonFile);

        Gson gson = new Gson();
        Student huanhuan = gson.fromJson(content, Student.class);

        System.out.println(huanhuan.getAge());
        System.out.println(huanhuan.getCar());
        System.out.println(huanhuan.getGrade());
        System.out.println(huanhuan.getId());
        System.out.println(huanhuan.getName());
        System.out.println(huanhuan.isHasGirlfriend());
        for(int i=0; i<huanhuan.getSubjects().length;i++){
            System.out.print(huanhuan.getSubjects()[i]+",");
        }
        System.out.println();

Generate Json
How to create a JSON object with GSON? Check the following code:

        Student shuaishuai = new Student();

        shuaishuai.setAge(23);
        shuaishuai.setCar(null);
        shuaishuai.setGrade(72.5);
        shuaishuai.setHasGirlfriend(true);
        shuaishuai.setId("1240031");
        shuaishuai.setName("Shuai Wang");
        shuaishuai.setSubjects(new String[]{"Internet", "Algorithm", "Database", "Java"});

        Gson ws = new Gson();
        System.out.println(ws.toJson(shuaishuai));

Handle Date type
We all know JSON does not have Date type to process date and time. GSON provides a way to handle Date type. Check the following code:

File jsonFile = new File(HandleDate.class.getResource("/json/xiaoxiao.json").getFile());
        String content = FileUtils.readFileToString(jsonFile);

        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setDateFormat("yyyy-mm-dd");

        Gson gson = gsonBuilder.create();
        StudentWithBirthday ylx = gson.fromJson(content, StudentWithBirthday.class);

        System.out.println(ylx.getBirthday());

Handle transient data
Sometimes we do not want private information in a Java object to be seen in a JSON. We can use the keyword “transient” when we’re defining instance variable for those private information. For example,

private transient double height;

Handle Naming Strategies
Sometimes we need to change the name of instance variables when they are shown in JSON. For example, one instance variable is called “grade”. We want to change it to “GPA” when it is converted into JSON. How to do it? Check it out,

Student linlin = new Student();

        linlin.setAge(24);
        linlin.setCar(null);
        linlin.setGrade(90.5);
        linlin.setHasGirlfriend(true);
        linlin.setId("408829");
        linlin.setName("Lin Zhang");
        linlin.setSubjects(new String[]{"Math", "English", "History", "Politics"});

        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setPrettyPrinting();
        gsonBuilder.setFieldNamingStrategy(new FieldNamingStrategy() {

            public String translateName(Field arg0) {
                if(arg0.getName().equals("grade"))
                    return "GPA";
                return arg0.getName();
            }
        });
        Gson zl = gsonBuilder.create();
        System.out.println(zl.toJson(linlin));

最後再說兩句(PS)
We now have two libraries which are JSON and GSON to process Json problem. By comparison, GSON is more powerful. GSON perform better when mapping Java objects to Json data. It can use “transient” to decide Whether a Json data contains this field. Moreover, it can deal with “Date” type. Additionally, it can convert a java bean to a Json data and convert a Json data into a java bean.

Welcome questions always and forever.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章