【发布时间】: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 -
哦,真的,谢谢你!