【问题标题】:How can I get some data frome json file with ArrayDeque?如何使用 ArrayDeque 从 json 文件中获取一些数据?
【发布时间】:2018-04-04 03:54:55
【问题描述】:

我尝试从这样的 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 文件的数据whit String

而且它不起作用。我收到此错误。

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

我该如何解决?

【问题讨论】:

    标签: android json arraydeque gson


    【解决方案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;
        }
    }
    

    结果

    【讨论】:

    • 我有一个新问题。现在,如果我在 Java 类中定义 String ,我可以将 String 解析为 Object。但是当我从文件中读取数据时,我会得到一个JsonParseExecption。我确认文件已正确读取。但这只是行不通。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-25
    • 2014-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-30
    相关资源
    最近更新 更多