当前位置:网站首页>@Jsonadapter annotation usage

@Jsonadapter annotation usage

2022-07-05 10:12:00 A bird carved in the desert

You really can use Gson Do you ?Gson Use guide ( Four ) - Simple books  

You really can use Gson Do you ?Gson Use guide ( One ) - Simple books  

Gson Use summary - Nuggets

Take over serialization and deserialization process

TypeAdapter Took over the serialization and deserialization process , and JsonSerializer and JsonDeserializer Then only take over the serialization and deserialization processes separately .

It works on POJO class Upper , Receive a parameter , And it must be TypeAdpater,JsonSerializer or JsonDeserializer One of these three .

Ahead JsonSerializer and JsonDeserializer All have to cooperate with GsonBuilder.registerTypeAdapter Use , But it's too troublesome to register every time you use it ,JsonAdapter Is to solve this pain point .

Use :

@JsonAdapter(UserTypeAdapter.class)
public final class User {
    .....
}
public class UserTypeAdapter implements JsonSerializer<User> {

    @Override
    public JsonElement serialize(User src, Type typeOfSrc, JsonSerializationContext context) {
        JsonObject jsonElement = new JsonObject();
        jsonElement.addProperty("name","serialize");
        return jsonElement;
    }
}
User user = new User(" I ",10);
Log.i("adapter","user:"+new Gson().toJson(user));// Direct use of simple new GSON() that will do , No configuration registration required 

原网站

版权声明
本文为[A bird carved in the desert]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050941162139.html