Json与Gson

JSON官网:http://json.org/json-zh.html
Gson:在github:https://github.com/google/gson

JSONOBejct缺点:
1从javaBean能转化为jsonObject,却不能反解析.
2JsonObect没有日期类型,因此javaBean中日期类型只能折中的写成String类型

Gson的优点就是解决了Json的缺点

特点:
JSON是Android SDK官方的库,适合做移动端

GSON适用于服务端开发

GSON的功能比json的JSONObject功能更加强大

 File file = new File(ReadJSONSample.class.getResource("/OSCAR.json").getFile());
        String content = FileUtils.readFileToString(file,"utf-8");

        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();                     
        DiaosiWithBirthday OSCAR = gson.fromJson(content,DiaosiWithBirthday.class); //json反向解析为Bean
        System.out.println(OSCAR.getBirthday().toLocaleString());

        //集合类解析
        System.out.println(OSCAR.getMajor());
        System.out.println(OSCAR.getMajor().getClass());
4//下面三行代码可以进行美化,不会再同一行输出
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setPrettyPrinting();
        gsonBuilder.setFieldNamingStrategy(new FieldNamingStrategy() {
            @Override
            public String translateName(Field f) {//自定义回调函数

                if (f.getName().equals("name")){
                    return "NAME";
                }
                return f.getName();
            }
        });
        Gson gson = gsonBuilder.create();
        //Gson gson = new Gson();
       // System.out.println(gson.toJson(OSCAR));

还有JSONObject在项目里未拷贝,因为GSON的功能要强大!!!!!!!!!!!!1

猜你喜欢

转载自www.cnblogs.com/xinglongbing521/p/10383195.html