How to convert json to Vector ? ClassCastException gson Android 4.4.2

核能气质少年 提交于 2019-12-13 21:26:31

问题


I have a problem to read json and convert it to Vector of objects, The weird part is this issue occurs only on Android 4.4.2 Device , and on emulator it's working.

Here is my code:

JsonReader reader = new JsonReader(new StringReader(string));

AllConversationsObject allConversationsObject = gson.fromJson(reader,AllConversationsObject.class);

allConversationObject.conversations.get(0)

Here is AllConversationsObject:

public class AllConversationsObject  {
    Vector<Conversation>  conversations;
    String bookmark;

    public Vector<Conversation> getConversations() {
        return conversations;
    }

    public void setConversations(Vector<Conversation> conversations) {
        this.conversations = conversations;
    }

    public String getBookmark() {
        return bookmark;
    }

    public void setBookmark(String bookmark) {
        this.bookmark = bookmark;
    }
}

The application crash on conversations.get(0) with this error:

Fatal Exception: java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to com.myapp.com.Conversation

Here is build.gradle :

compile 'com.google.code.gson:gson:2.3'

Here is the Json:

{
  "bookmark": "string",
  "conversations": [
    {},
    {}
  ]
}

what's the problem ? Thank you


回答1:


Instead of Vector use List but my concern is in the bookmark field.

According to the json it is an array of some objects, but you are modeling it as a String. You should declare it as List<Object> or any List<String> if you are sure that bookmark is array of String



来源:https://stackoverflow.com/questions/42553204/how-to-convert-json-to-vector-classcastexception-gson-android-4-4-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!