Search code examples
androidjsonarraydequegson

How can I get some data frome json file with ArrayDeque?


I try to get some data from json file like this.

[
  {
    "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
  }
]

And defined a class like this.

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

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

I tried to ues GSON to parse the json data as ArrayDeque<TextData> like this

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

Method getJson will get json file's data whit String.

And it's dosen't work. I get this error.

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

How can I fix it?


Solution

  • Try this

        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() + "");
        }
    

    model class

    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