Gson未序列化值

时间:2019-05-06 13:30:07

标签: java json serialization gson

这是我的Json回复。

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

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

这是我的Model类。

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 );
    }
}

1 个答案:

答案 0 :(得分:1)

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

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

也许您的回答有问题吗?