如何使用ArrayDeque从json文件中获取一些数据?

时间:2018-04-04 03:54:56

标签: android json arraydeque gson

我尝试从这样的json文件中获取一些数据。

[
  {
    "type": "text",
    "content": "test test test",
    "time": 100
  },
  {
    "type": "text",
    "content": "abcedfg",
    "time": 100
  },
  {
    "type": "text",
    "content": "some data",
    "time": 100
  },
  {
    "type": "text",
    "content": "1234567",
    "time": 100
  }
]

定义了这样一个类。

class TextData {
    String type;
    String content;
    long time;

    TextData(String type, String content, long time) {
        this.type = type;
        this.content = content;
        this.time = time;
    }
}

我试图让GSON将json数据解析为ArrayDeque<TextData>,如此

    ArrayDeque<TextData> textDatas = 
            new Gson().fromJson(getJson(fileName), ArrayDeque.class);

方法getJson将获取json文件的数据白色String

它的工作正在进行中。我收到了这个错误。

failed to deserialize json object "" given the type class java.util.ArrayDeque

我该如何解决?

1 个答案:

答案 0 :(得分:1)

试试这个

    Gson gson = new Gson();
    Type listType = new TypeToken<List<TextData>>() {
    }.getType();
    List<TextData> arralist = (List<TextData>) gson.fromJson(response, listType);

    for (int i = 0; i < arralist.size(); i++) {
        Log.e("Content", arralist.get(i).getContent());
        Log.e("type", arralist.get(i).getType());
        Log.e("time", arralist.get(i).getTime() + "");
    }
  

模型类

public class TextData {
    String type;
    String content;
    long time;

    public TextData(String type, String content, long time) {

        this.type = type;
        this.content = content;
        this.time = time;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public long getTime() {
        return time;
    }

    public void setTime(long time) {
        this.time = time;
    }
}

<强> RESULT

enter image description here