Gson 仅使用 false 反序列化布尔值 JSON,而不管输入

Gson deserialize the boolean JSON only with false, regardless to input

我的对象由五个字段组成:

    public class ConfigurationItem {

    @SerializedName("show_interest")
    boolean show_interest;
    @SerializedName("bid_with_price")
    boolean bid_with_price;
    @SerializedName("anonymous_orders")
    boolean anonymous_orders;
    @SerializedName("orders_progress_status")
    boolean orders_progress_status;
    @SerializedName("orders_progress_messages")
    boolean orders_progress_messages;
}

我从网络服务器解析这些项​​目并接收这样的字符串:

{
"ordersProgressStatus":true,
"showInterest":false,
"anonymousOrders":true,
"bidWithPrice":true,
"ordersProgressMessages":true
}

我收到 JSON 并将其保存到 SharedPreferences,如下所示:

public static void saveCurrentConfiguration(Context mContext, JSONObject jsonObject ) {
        SharedPreferences sharedPreferences = mContext.getApplicationContext().getSharedPreferences(Constants.SHARED_PREFS_NAME, Context.MODE_PRIVATE);
            SharedPreferences.Editor prefsEditor = sharedPreferences.edit();
            prefsEditor.putString(Constants.SHARED_CURRENT_CONFIG, jsonObject.toString());
            prefsEditor.apply();
    }

但是当我想读取保存的对象时:

public static ConfigurationItem getCurrentConfiguration(Context mContext)
{
    SharedPreferences sharedPreferences = mContext.getApplicationContext().getSharedPreferences(Constants.SHARED_PREFS_NAME, Context.MODE_PRIVATE);
    Gson gson = new Gson();
    String json = sharedPreferences.getString(Constants.SHARED_CURRENT_CONFIG, null);
    ConfigurationItem configurationItem = gson.fromJson(json, ConfigurationItem.class);
    Log.i(TAG + " loaded config", configurationItem.toString());
    return configurationItem;
}

configurationItem 中我只得到错误的值。此外,从 SharedPreference 读取的字符串是正确的,但是当我使用 Gson 进行反序列化时,对象填充了错误的值。

有什么解决办法?

当使用注释 @SerializedName 时,它引用 JSON 字符串中的键值。因此,与其使用 @SerializedName("show_interest") 序列化 "showInterest" 中的值,不如使用 @SerializedName("showInterest")

当您不想将 JSON 键的名称与字段名称相关联时,使用序列化名称很方便。例如,当您更喜欢使用 JAVA 标准约定为私有字段添加前缀 m 时,例如 private boolean mShowInterest;,那么当您稍后将字段名称重构为其他名称时,您可以进行简单的重构,或者如果 JSON 键发生变化,您必须更改注释。