GSON@JSON

来源:互联网 发布:php 最值得阅读源码 编辑:程序博客网 时间:2024/06/05 03:48

GSON创建JSON

Gson gson=new Gson;System.out.println(gson.toJson(传javabean对象));


Gson 可以用注解的方式实现 列名转化:@SerializedName("key的字符串");public class Diaosi {@SerializedName("Name")private String name;@SerializedName("School")private String school;}

生成JSON数据

GsonBuilder gsonBuilder=new GsonBuilder();gsonBuilder.setPrettyPrinting();// 可以使打印出来的json 格式化Gson gson=gsonBuilder.create();
gsonBuilder.setFieldNamingStrategy(new FieldNamingStrategy(){ 
        if(f.getName().equals("name")){              return "NAME";         }              return f.getName();
})
 System.out.println(gson.toJson(传javabean对象));

Gson 可以使用transient隐藏不显示列名:javaBean中列属性private后面添加 transianteg:private transient String ignore;GSON解析
在java获取json数据,首先把json文件实例化为file对象,然后用file的工具类的静态方法转换成字符串,如FileUtils.readFileToString(file),然后实例化Gson对象,再调用fromJson方法解析json。JSONObject可以将*.json文件解析成一个它的对象;Gson可以正向的生成,也可以解析成自己定义的一个JavaBean的对象package gson;import java.io.File;import java.io.IOException;import org.apache.commons.io.FileUtils;import com.google.gson.Gson;import bean.Diaosi;import json.ReadJSONSample;public class GsonReadSample {public static void main(String[] args) throws IOException {File file=new File(ReadJSONSample.class.getResource("/json.json").getFile());String content=FileUtils.readFileToString(file);Gson gson=new Gson();JAVABean对象  json=gson.fromJson(content, JAVABean对象.class);System.out.println(json);}}

GSON日期格式转换:
   File file = new File(GsonCreateSample.class.getResource("/json.json").getFile());   String content = FileUtils.readFileToString(file);   Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();   PersonWithDate per = gson.fromJson(content,PersonWithDate.class);   System.out.println(per.getBirthday().toLocalString(0);

集合类解析

Gson 支持集合类的声明属性:    public class Teacher{        private List<String> major;    }
    System.out.println(对象.getMajor());
















原创粉丝点击