【问题标题】:Gson deserialize the boolean JSON only with false, regardless to inputGson 仅使用 false 反序列化布尔 JSON,无论输入
【发布时间】:2015-07-11 11:13:52
【问题描述】:

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

    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 进行反序列化时,对象填充了错误的值。

有什么解决办法?

【问题讨论】:

  • 我认为 JSON 对象的键是不同的,在 ConfigurationItem 对象中你使用了 show_interest 并且收到的对象有 showInterest
  • 哦,真的,谢谢你!

标签: java android json gson


【解决方案1】:

当使用注解 @SerializedName 时,它引用 JSON 字符串中的键值。因此,不要执行@SerializedName("show_interest") 来序列化来自"showInterest" 的值,而是执行@SerializedName("showInterest")

当您不想将 JSON 键的名称与字段名称联系起来时,使用序列化名称会很方便。例如,当您更喜欢使用 m 前缀私有字段的 JAVA 标准约定时,例如 private boolean mShowInterest;,因此当您稍后将字段名称重构为其他名称时,您可以进行简单的重构,或者如果 JSON 键更改您有更改注释。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多