Gson反序列化JSON时可以使用setter吗? [英] Is possible to use setters when Gson deserializes a JSON?

查看:574
本文介绍了Gson反序列化JSON时可以使用setter吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么方法给定类的设置方法,在使用Gson的 fromJson 方法时使用?



我想这样做是因为对于每个字符串目标类的全局变量进行修剪。



是否有任何GSON API注释?



我知道GSON提供了编写自定义序列化器/反序列化器的功能,但是我想知道是否有另一种方法我实现了一个 JsonDeserializer< String> ,并注册了它。

它在 GsonBuilder 上。因此,对于接收到的所有字符串字段,Gson将使用我的 StringGsonTypeAdapter 来反序列化值。



以下是我的代码:

 导入静态net.hugonardo.java.commons.text.StringUtils.normalizeSpace; 
导入静态net.hugonardo.java.commons.text.StringUtils.trimToNull;

final class StringGsonTypeAdapter实现JsonDeserializer< String> {

private static final StringGsonTypeAdapter INSTANCE = new StringGsonTypeAdapter();

static StringGsonTypeAdapter实例(){
return INSTANCE;

$ b @Override
public String deserialize(JsonElement jsonElement,Type type,
JsonDeserializationContext jsonDeserializationContext)throws JsonParseException {
return normalizeSpace(trimToNull(jsonElement。符getAsString()));




$ b

...和我的GsonBuilder:

  Gson gson = new GsonBuilder()
.registerTypeAdapter(String.class,StringGsonTypeAdapter.instance())
.create ())


Is there any way the set methods of a given class, are used when using Gson's fromJson method?

I would like to do this because for every String global variable of the target class a trim is made.

Is there any GSON API annotation for this?

I am aware that GSON provides the ability to write custom serializers/deserializers but I would like to know if there is another way to achieve this.

解决方案

I implemented a JsonDeserializer<String> and registered it on GsonBuilder. So, to all String fields received, Gson will use my StringGsonTypeAdapter to deserialize the value.

Below is my code:

import static net.hugonardo.java.commons.text.StringUtils.normalizeSpace;
import static net.hugonardo.java.commons.text.StringUtils.trimToNull;

final class StringGsonTypeAdapter implements JsonDeserializer<String> {

    private static final StringGsonTypeAdapter INSTANCE = new StringGsonTypeAdapter();

    static StringGsonTypeAdapter instance() {
        return INSTANCE;
    }

    @Override
    public String deserialize(JsonElement jsonElement, Type type, 
        JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        return normalizeSpace(trimToNull(jsonElement.getAsString()));
    }
}

...and my GsonBuilder:

Gson gson = new GsonBuilder()
    .registerTypeAdapter(String.class, StringGsonTypeAdapter.instance())
    .create())

这篇关于Gson反序列化JSON时可以使用setter吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆