java - Gson 只用 false 反序列化 boolean JSON,不管输入

标签 java android json gson

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

    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 标准约定为私有(private)字段添加前缀 m 时,例如 private boolean mShowInterest; 所以当您稍后将字段名称重构为您可以做的其他事情时一个简单的重构,或者如果 JSON 键发生变化,您必须更改注释。

关于java - Gson 只用 false 反序列化 boolean JSON,不管输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31356578/

相关文章:

java - 异常类不工作

java - 在java中使用axom-api解码X-JWT-Assertion

通过 NFC WiFi 类型参数的 Android 设备所有者

javascript - 仅从 javascript 数组获取唯一键,其中键和值都是动态的

ruby-on-rails - 在 as_json 中订购嵌套关联

c# - 使用 DataContractJsonSerializer 序列化 Dictionary<> 对象

java - 可配置(例如 XML)Java Bean 到 Bean 映射框架

android - 如何检查用户是否禁用了通知声音?

android - 如何为 float 操作按钮内的图标设置动画

java - 接受任何内容并保留签名的方法?