我的对象包含五个字段:
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;
}
我从Web服务器解析这些项目并接收如下字符串:
{
"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
进行反序列化时,该对象将填充错误的值。
可以解决什么问题?
答案 0 :(得分:2)
使用注释def process_file(filename):
title_line = 3 # indexing starts at 0, so one less than 4
cols_to_keep = [0, 2, 3]
# load entire CSV file into list (not good for massive files)
f_lines = open(filename).readlines()
out_file = open("out.csv", "w")
f_lines = [line.strip().split(",") for line in f_lines] # split each line in f_lines
if os.stat("file").st_size == 0: # if file is empty, add title line
out_file.write(",".join(f_lines[title_line]))
for line in f_lines[title_line:]: # for each line after title line
new_line = []
for col_index in cols_to_keep:
new_line.append(line[col_index])
out_file.write(",".join(new_line))
时,它引用JSON字符串中的键值。因此,不要执行@SerializedName
来序列化来自@SerializedName("show_interest")
的值"showInterest"
如果您不想将JSON密钥的名称绑定到字段名称,则使用序列化名称很方便。例如,当您更喜欢使用JAVA标准惯例为私有字段添加@SerializedName("showInterest")
前缀m
时,所以稍后您将字段名称重构为其他内容时,您可以执行简单的重构,或者如果使用JSON密钥改变你的方法必须改变注释。