【问题标题】:Gson not serializing valuesGson没有序列化值
【发布时间】:2019-05-06 13:30:07
【问题描述】:

这是我的 Json 响应..

{"averageYield":15.0,"maxYield":15.0,"personalYield":100.0}

我正在使用 Gson 来序列化这个 Json,但它将所有字段的值存储为 0。

这是我的模型类。

public class GetYieldComparisonResponse extends RealmObject {

    @SerializedName("averageYield")
    private double averageYield;

    @SerializedName("maxYield")
    private double maxYield;

    @SerializedName("personalYield")
    private double personalYield;

    public double getAverageYield() {
        return averageYield;
    }

    public void setAverageYield(double averageYield) {
        this.averageYield = averageYield;
    }

    public double getMaxYield() {
        return maxYield;
    }

    public void setMaxYield(double maxYield) {
        this.maxYield = maxYield;
    }

    public double getPersonalYield() {
        return personalYield;
    }

    public void setPersonalYield(double personalYield) {
        this.personalYield = personalYield;
    }
}

我使用 Realm 来存储数据,但是每个字段的存储值都是 0。

GetYieldComparisonResponse getYieldComparisonResponse = GsonUtils.fromGson( basicResponse.getResponse(), GetYieldComparisonResponse.class );

这是我的 GsonUtils.java

//  This Class is useful for mapping Json into Java Objects and vice versa.
public class GsonUtils {

    private static final Gson gson = new Gson();

    //  This will Convert Java Objects into JSON String...
    public static String toGson(Object object) {
        return gson.toJson( object );
    }

    //  Gives Java Objects from JSON
    public static <T> T fromGson(String json, Class<T> type) {
        return gson.fromJson( json, type );
    }

    //  get Array...
    public static Object jsonToArray(String json, Type type) {
        return gson.fromJson( json, type );
    }
}

【问题讨论】:

  • basicResponse 是什么类型,basicResponse.getResponse() 返回什么类型?
  • 这是 Json 响应。 {"averageYield":15.0,"maxYield":15.0,"personalYield":100.0} 这个。
  • 我没有看到 将所有字段的值存储为 0。 在此响应中。
  • @Antoniossss 我正在使用领域,所以当它将 json 序列化为对象时,gson 将所有值设为 0。
  • @AviPatel 你还没有回答我的问题。 Json Response 可能不是一个类型,因为它包含一个空格。我们也需要这个包。

标签: java json serialization gson


【解决方案1】:

如果我做这样的事情,它会完美地工作:

GetYieldComparisonResponse getYieldComparisonResponse = GsonUtils.fromGson( "{\"averageYield\":15.0,\"maxYield\":15.0,\"personalYield\":100.0}", GetYieldComparisonResponse.class );

也许你的回复有问题?

【讨论】:

  • 我不这么认为,这应该是问题所在,因为您所做的与 basicResponse.getResponse() 相同。
  • 这也没有帮助。
猜你喜欢
  • 2021-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-12
  • 1970-01-01
相关资源
最近更新 更多