代码之家  ›  专栏  ›  技术社区  ›  Touki Liu

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

  •  0
  • Touki Liu  · 技术社区  · 8 年前

    我试图像这样从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 回复  |  直到 7 年前
        1
  •  1
  •   AskNilesh    8 年前

    试试这个

        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;
        }
    }
    

    结果

    enter image description here