Android Kotlin:JSONObject可以解析自定义对象吗?
我正在尝试将Map对象存储到android共享首选项中,下面是代码:Android Kotlin:JSONObject可以解析自定义对象吗?,android,json,kotlin,Android,Json,Kotlin,我正在尝试将Map对象存储到android共享首选项中,下面是代码: private fun setMap(context: Context, key: String, value: Map<String, Any>) { val editor = PreferenceManager.getDefaultSharedPreferences(context).edit() val jsonObject = JSONObject(value)
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()
}
private-fun-setMap(上下文:上下文,键:字符串,值:Map){
val editor=PreferenceManager.getDefaultSharedReferences(上下文).edit()
val jsonObject=jsonObject(值)
val jsonString=jsonObject.toString()
putString(key,jsonString)
editor.apply()
}
如果我的映射类型是Map或Map
,那么上面的代码工作正常,第2行的jsonObject是{“test”,“123”}
但是,如果我的映射包含任何自定义对象,如Map即Map
,则第2行的i jsonObject是{“test”,null}
JSONObject可以解析自定义对象吗?您可以使用Gson库或此库解析json(即,将对象转换为json并将json转换为对象):在这种情况下,您必须查看
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.
*/
/**
*如有必要,包装给定对象。
*
*如果对象为null或,则返回{@link#null}。
*如果对象是{@code JSONArray}或{@code JSONObject},则不需要包装。
*如果对象为{@code NULL},则不需要包装。
*如果对象是数组或{@code Collection},则返回等效的{@code JSONArray}。
*如果对象是{@code-Map},则返回等效的{@code-JSONObject}。
*如果对象是基本包装类型或{@code String},则返回该对象。
*否则,如果对象来自{@code java}包,则返回{@code toString}的结果。
*如果包装失败,则返回null。
*/
在您的例子中,我猜您的map值不符合任何返回非null值的标准,这是我对非java.*
nonJSON*
对象所期望的
话虽如此,我建议不要将复杂的对象和结构存储在SharedReferences
中(这不是最佳选择),并建议使用数据库。但是,如果你选择了这条路线,一定要看看路线