Gson的使用-4
程序员文章站
2024-03-16 09:36:34
...
简单自定义序列化
public class User {
private static final String APPLICATION_USER = "USER";
private String name;
private int age;
public class UserData{
private int id;
private String name;
}
}
JsonSerializer<User.UserData> jsonSerializer = new JsonSerializer<User.UserData>() {
@Override
public JsonElement serialize(User.UserData src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("id",src.getId());
return jsonObject;
}
};
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(User.class,jsonSerializer);
简单自定义反序列化
JsonDeserializer<User.UserData> jsonDeserializer = new JsonDeserializer<User.UserData>() {
@Override
public User.UserData deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
int id = json.getAsInt();
return
}
}
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(User.class,jsonderializer);
jsonAdapter()注解;
自定义序列化和反序列化的过程
public class MerchantListSerializer implements JsonSerializer<List<Merchant>> {
@Override
public JsonElement serialize(List<Merchant> src, Type typeOfSrc, JsonSerializationContext context) {
JsonArray jsonMerchant = new JsonArray();
for (Merchant merchant : src) {
jsonMerchant.add("" + merchant.getId());
}
return jsonMerchant;
}
}
public class UserSubscriptionAnnotation {
String name;
String email;
int age;
boolean isDeveloper;
// new!
@JsonAdapter(MerchantListSerializer.class)
List<Merchant> merchantList;
}
上一篇: p-7-9求逆序对数目