我正在尝试将Map对象存储到android共享首选项中,代码如下:
private fun setMap(context: Context, key: String, value: Map<String, Any>) {
val editor = PreferenceManager.getDefaultSharedPreferences(context).edit()
val jsonObject = JSONObject(value)
val jsonString = jsonObject.toString()
editor.putString(key, jsonString)
editor.apply()
}如果我的地图是Map<String, String> or Map<"test","123">类型的,那么上面的代码就可以很好地工作,并且第2行上的jsonObject是{"test", "123"}。
但是,如果我的地图包含任何自定义对象,如Map<String, CustomObject> i.e. Map<"test", CustomObject()>,则第2行上的I jsonObject为{"test", null}。
JSONObject可以解析自定义对象吗?
发布于 2020-01-26 04:53:11
您可以使用Gson库或以下库解析json (即将对象转换为json,并将json转换为对象):https://github.com/Kotlin/kotlinx.serialization
发布于 2020-01-26 07:07:16
在这种情况下,您必须查看JSONObject的实现。
有关JSONObject(Map)构造函数的参数的文档说明
* @param copyFrom a map whose keys are of type {@link String} and whose
* values are of supported types.但是要找出有效值的构成要素,您必须查看在构造函数中调用的wrap(entry.getValue())。wrap的文档说明:
/**
* Wraps the given object if necessary.
*
* <p>If the object is null or , returns {@link #NULL}.
* If the object is a {@code JSONArray} or {@code JSONObject}, no wrapping is necessary.
* If the object is {@code NULL}, no wrapping is necessary.
* If the object is an array or {@code Collection}, returns an equivalent {@code JSONArray}.
* If the object is a {@code Map}, returns an equivalent {@code JSONObject}.
* If the object is a primitive wrapper type or {@code String}, returns the object.
* Otherwise if the object is from a {@code java} package, returns the result of {@code toString}.
* If wrapping fails, returns null.
*/在您的例子中,我猜测您的map值不满足返回非空值的任何条件,这是我对非java.*非JSON*对象的期望。
话虽如此,我还是建议不要在SharedPreferences中存储复杂的对象和结构(它对此并不是最好的),并建议使用数据库。但是,如果您设置了此路线,请务必查看Kotlin Serialization library。
https://stackoverflow.com/questions/59913001
复制相似问题