开发者

Android Parceling an object with JSONArray member

开发者 https://www.devze.com 2023-03-18 19:11 出处:网络
I\'m developing an Android app and I\'m in a situation where I need to start a new activity by passing in an object of a Class that I created into a bundle so it can be used in the new activity.

I'm developing an Android app and I'm in a situation where I need to start a new activity by passing in an object of a Class that I created into a bundle so it can be used in the new activity.

I've researched on how to do this and it seems like for objects the best way is to make them Parcelable. However, the problem is that one of the fields for that object's class is a JSONArray type and it doesn't seem like JSONArray is supported? Or maybe I just haven't looked hard enough or I missed something, but I've been searching for hours and i still couldn't find anything.

To be more specific, I need to parcel the fields of my ob开发者_如何学Cject with a

writeX();

where the X can such things as ints, strings etc. However, like I just said, one of my fields is a JSONArray type for a specific reason (I do not wish to change this in anyway) and it seems like Parcel doesn't support this?

Thanks


thanks for the reply, but unfortunately this JSONArray contains way too much varying info for this to work (it has integers strings, JSONObjects and even JSONArrays -_-). I have however found a way, and this is to convert the entire JSONArray to a string by using the toString method. This makes it possible to put it into a Bundle. I don't really like doing it this way... but I don't have much time to be thinking on this for too long :P. Thanks anyway


I was able to put an ArrayList of JSONObjects into a bundle using putSerializable rather than putParcelable.


Do you know ahead of time what the type the JSONArray is of? If so you can convert the JSONArray to a List of the known type.

JSONArray is not supported here because its not a class that implements Parcelable. If you absolutely have no control over the choice of that JSONArray type you need to convert the JSONArray to a list.

The following code converts a JSONArray of a known String type to an ArrayList:

ArrayList<String> list = new ArrayList<String>();    
JSONArray jsonArray = (JSONArray)jsonObject;
if (jsonArray != null) {
   for (int i=0;i<jsonArray.size();i++){
    list.add(jsonArray.get(i).toString());
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号