我的对象由五个字段组成:
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/