Gson使用总结

来源:互联网 发布:广发交易软件 编辑:程序博客网 时间:2024/06/02 21:11

1、环境

使用gson版本2.3.1,支持不定义对象对json结果的遍历(见第9点)。


2、常见的标签

@SerializedName("名称")   可以设置字段生成json文件的时候是否是需要跟换名称

@Expose  设置序列化的时候是否包括这个字段,默认为true


@Since和@Until注解,使用方法:当前版本(GsonBuilder中设置的版本) 大于等于Since的值时该字段导出,小于Until的值时该该字段导出。


详细使用见下:

public class Example33 {  public static void main(String[] args) {    Gson gson = new GsonBuilder().setVersion(2.0).create();    String json = gson.toJson(new ExampleClass());    System.out.println("Output for version 2.0...");    System.out.println(json);        gson= new GsonBuilder().setVersion(1.0).create();    json = gson.toJson(new ExampleClass());    System.out.println("\nOutput for version 1.0...");    System.out.println(json);        gson= new Gson();    json = gson.toJson(new ExampleClass());    System.out.println("\nOutput for No version set...");    System.out.println(json);  }} class ExampleClass{  String field=  "field";  // this is in version 1.0  @Since(1.0) String newField1 = "field 1";  // following will be included in the version 1.1  @Since(2.0) String newField2 = "field 2";}



3、通过类型排除

ExclusionStrategy myExclusionStrategy = new ExclusionStrategy() {@Overridepublic boolean shouldSkipField(FieldAttributes fa) { return fa.getName().startsWith("serializationFieldSet")||fa.getName().startsWith("unknownFieldSet");}@Overridepublic boolean shouldSkipClass(Class<?> clazz) {return false;}};    Gson  gson = new GsonBuilder()    .setExclusionStrategies(myExclusionStrategy)    .setPrettyPrinting()    .create();
其中shouldSkipField()是根据字段名字来过滤是否解析,shouldSkipClass()是根据类型来判断是否解析

4、格式化输出

 Gson  gson = new GsonBuilder().setPrettyPrinting().create();


5、特殊类型

时间处理

Gson gson = new GsonBuilder()    .setDateFormat("yyyy-MM-dd HH:mm:ss")    .create();  


6、类型适配

实现:自定义一个枚举类

调用方法:

Gson gson = new GsonBuilder().registerTypeAdapterFactory(newIntEnumTypeAdapterFactory());


类实现:

//适配的gson方法public class IntEnumTypeAdapterFactory implements TypeAdapterFactory {@Overridepublic <Enum> TypeAdapter<Enum> create(Gson gson, TypeToken<Enum> type) {Class<Enum> rawType = (Class<Enum>) type.getRawType();if (!rawType.isEnum()) {return null;}//默认值final Map<String, Enum> defaultValue = new HashMap<String, Enum>();//Enum映射值final Map<String, Integer> valueMap = new HashMap<String, Integer>();for (Enum constant : rawType.getEnumConstants()) {if (constant instanceof EnumInteger) {EnumInteger enumInteger = (EnumInteger) constant;valueMap.put(constant.toString(), enumInteger.intValue());} elsedefaultValue.put(constant.toString(), constant);}return new TypeAdapter<Enum>() {public void write(JsonWriter out, Enum value) throws IOException {if (value == null) {out.nullValue();} else {if (value instanceof EnumInteger)out.value(valueMap.get(value.toString()));elseout.value(defaultValue.get(value.toString()).toString());}}public Enum read(JsonReader reader) throws IOException {if (reader.peek() == JsonToken.NULL) {reader.nextNull();return null;} else {return defaultValue.get(reader.nextString());}}};

说明:主要作用就是把继承EnumInteger的枚举类,解析为数字,因为如果不做任何改变,解析后返回的值是字符串,不是数字。Write方法首先判断是否为枚举类,若是再判断属性是否是EnumInteger类型,如果是就把字符串,数字形式的map,如果不是就存为字符串,枚举类形式的map,反序列化时,直接根据字符串来取值,就可以取到数字。


7、替换默认类型

仍然使用适配方法,支持Data和long之间转化,文档见:http://my.oschina.net/vernon/blog/364379


public class DateSerializer implements JsonSerializer<Date> {    public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {        return new JsonPrimitive(src.getTime());    }}public class GsonBuilderUtil {    public static Gson create() {        GsonBuilder gb = new GsonBuilder();        gb.registerTypeAdapter(java.util.Date.class, new DateSerializer()).setDateFormat(DateFormat.LONG);        gb.registerTypeAdapter(java.util.Date.class, new DateDeserializer()).setDateFormat(DateFormat.LONG);        Gson gson = gb.create();        return gson;    }}


8、其他

html转义:

gson = new GsonBuilder().disableHtmlEscaping().create();


9、不使用映射对象的简单json处理

上代码

public static void testNoObjectMapping(){String result = "{\"ResultCode\":200,\"JsonData\": \"{\"impresa\":\"测试11111222333444\"}}";Gson gson = new Gson();//简单的linkedTree处理LinkedTreeMap<String, Object>  treeMap = (LinkedTreeMap<String, Object>)gson.fromJson(result, Object.class);//按照树的属性进行遍历,满足不定义对象的需要Iterator<Entry<String, Object>> iterator = treeMap.entrySet().iterator();while (iterator.hasNext()) {Entry<String, Object> entry= (Entry<String, Object>) iterator.next();System.out.println("key is: " + entry.getKey() + " value is:"+entry.getValue());}//简单遍历keySet<String> sets = treeMap.keySet();for (String key : sets) {System.out.println(key);}}



10、参考文档

http://www.javacreed.com/gson-typeadapter-example/

http://www.programcreek.com/java-api-examples/index.php?api=com.google.gson.TypeAdapterFactory

http://my.oschina.net/vernon/blog/364379

http://blog.csdn.net/wangdonghello/article/details/38922195

http://jackyrong.iteye.com/blog/2004374

http://blog.csdn.net/linjiaxingqqqq/article/details/7238235

推荐系列文章

http://www.jianshu.com/p/e740196225a4

1 0