gpt4 book ai didi

Android - json-smart反序列化问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:14:28 25 4
gpt4 key购买 nike

当我尝试传递 json-smart JSONObject 时,我的 Android 代码出现了一个奇怪的问题或 JSONArray作为可序列化的数据作为 Intent 可序列化的额外数据。 Json-smart是非常快速和精简的 JSON 解析器实现,我强烈推荐它。 JSONObject延伸HashMap<String, Object>JSONArray延伸ArrayList<Object>开销很小。这些对象都不会覆盖 Object#writeObject#read

问题是:

如果我在说 Fragment#onSaveInstanceState(String, JSONObject) 中使用这些对象一切正常。如果我在纯 Java 示例项目中序列化/反序列化这些对象,它将再次按预期工作。但是,如果我使用 Intent#putExtra(String, JSONObject)然后尝试通过执行

获取我的 JSONObject
JSONObject json = (JSONObject) intent.getSerializableExtra("JSON");

我会得到 ClassCastException因为该方法返回的是普通的 HashMap (如果是 JSONArray,它是 ArrayList)。此外,如果我查看 map /数组内部,内容将完全删除对 JSONObject/JSONArray 的任何引用,并替换为 HashMaps/ArrayLists

filed the ticket并提供了示例项目,但不幸的是,作者在没有解决的情况下关闭了它,所以我只是想深入了解它。如果你去看票,它附有简单的项目。

有没有办法解决这个问题?现在我必须将 JSONObject 或 JSONArray 转换为 String 并将其重新解析回对象,例如:

JSONArray feeds = (JSONArray) JSONValue.parse(intent.getStringExtra(RAW_FEED));

最佳答案

实现android.os.Parcelable:

http://developer.android.com/reference/android/os/Parcelable.html

基本上,您在对象中添加了一些额外的代码来解释如何对其进行序列化和反序列化。这就是为什么它会丢失您的类信息,它不知道如何正确序列化它。如果我是你,我会通过你的 Intent 传递一个值对象而不是一个 JSON 对象,因为你知道你确切地知道你传递的是什么类型的对象。您以这种方式检索您的 Parcelable:

getIntent().getExtras().getParcelable(key); 

我知道这可能看起来像是一些额外的代码,但实际上我认为这是一种在 Activity 之间共享数据的非常干净的方式。您正在传递一个强类型,您指定了如何收缩/膨胀它,并且您的 Activity 实际上不需要彼此有任何工作知识。

在您的值对象中,您只需像这样填写空白:

/** Parcelable implementation: deserialize object
* @param in Parcel object containing the data for this object
* @return a Person object */
public Person( Parcel in ) {
String[] data = new String[2];
in.readStringArray(data);
this.firstName = data[0];
this.lastName = data[1];
}

/** Parcelable implementation code */
public int describeContents() {
return 0;
}

/** Parcelable implementation: Serialize object to be passed between activities via Intent
* @param dest The parcel to transport the object
* @param flags refer to Parcelable api
* @return nothing */
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray( new String[] {
this.firstName,
this.lastName,
});
}

希望这会有所帮助,可能比您正在寻找的代码多一点,但它是一个真正干净的解决方案,因为当目标 Activity 获取对象时,您不必担心反序列化,这意味着 Activity 中的代码更干净。胖模型,干净的 View :)

关于Android - json-smart反序列化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8449993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com