首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JSONObject可以解析自定义对象吗?

JSONObject可以解析自定义对象吗?
EN

Stack Overflow用户
提问于 2020-01-26 04:10:20
回答 2查看 309关注 0票数 0

我正在尝试将Map对象存储到android共享首选项中,代码如下:

代码语言:javascript
复制
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可以解析自定义对象吗?

EN

回答 2

Stack Overflow用户

发布于 2020-01-26 04:53:11

您可以使用Gson库或以下库解析json (即将对象转换为json,并将json转换为对象):https://github.com/Kotlin/kotlinx.serialization

票数 0
EN

Stack Overflow用户

发布于 2020-01-26 07:07:16

在这种情况下,您必须查看JSONObject的实现。

有关JSONObject(Map)构造函数的参数的文档说明

代码语言:javascript
复制
 * @param copyFrom a map whose keys are of type {@link String} and whose
 *     values are of supported types.

但是要找出有效值的构成要素,您必须查看在构造函数中调用的wrap(entry.getValue())wrap的文档说明:

代码语言:javascript
复制
/**
 * 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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59913001

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档