gson高级使用


> 类型格式TypeToken

Type listType = new TypeToken<ArrayList<Person>>(){}.getType();

> 时间输出格式

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

> 别名

String JSON_DATA_STRING = {
    nick_name: "sagomilk"
}

public class Person {   
    @SerializedName("nick_name")
    public String name;
}

gson.fromJson(JSON_DATA_STRING, Person.class);

> 支持null输出

Gson includeNullsGson = gsonBuilder.serializeNulls().create();

> 禁用html转义

Gson unescapingGson = new GsonBuilder().disableHtmlEscaping().create();

> 通过访问修饰符控制序列化和反序列化

访问修饰符包括:publicprivateprotectedstaticfinal等,注意:static 会自动被排除。

   public class User {  
        private String name;  
        public boolean sex;  
        static int age;  
    final String homeAddress;  
    }  

    Gson gson = new GsonBuilder().excludeFieldsWithModifiers(
    Modifier.FINAL,Modifier.PRIVATE).create();  
    System.out.println(gson.toJson(user));  
    // 结果:{"sex":true}  

> 多版本支持

class VersionClass{
    @Since(1.0) 
    String versionOneField = "1.0";

    @Since(2.0) 
    String versionTwoField = "2.0";
}

Gson gson = new GsonBuilder().setVersion(1.0).create();

> Serializer

private class DateTimeSerializer implements JsonSerializer<DateTime> {
  public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context) {
    return new JsonPrimitive(src.toString());
  }
}

> Deserializer

private class DateTimeDeserializer implements JsonDeserializer<DateTime> {
  public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
      throws JsonParseException {
    return new DateTime(json.getAsJsonPrimitive().getAsString());
  }
}

> Serialization 和 Deserialization

GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(MyType2.class, new MyTypeAdapter());
gson.registerTypeAdapter(MyType.class, new MySerializer());
gson.registerTypeAdapter(MyType.class, new MyDeserializer());
gson.registerTypeAdapter(MyType.class, new MyInstanceCreator());

> Array



 - 直接解析成数组

    Person[] foos = gson.fromJson(JSON_DATA_STRING, Person[].class);
    List<Person> fooList = Arrays.asList(foos);



 - 解析成为List

    Type listType = new TypeToken<ArrayList<Person>>(){}.getType();
    ArrayList<Person> foos = gson.fromJson(JSON_DATA_STRING, listType);

> Map

如果没有对应的Object class,可以直接使用Map.class,但是使用的时候需要执行转换

Map m = gson.fromJson(JSON_DATA_STRING, Map.class);

> 命名风格setFieldNamingPolicy

 new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES).create();

> 美化

GsonBuilder gsonBuilder = new GsonBuilder();
Gson prettyGson = gsonBuilder.setPrettyPrinting().create();
展开阅读全文

没有更多推荐了,返回首页