How to read JSON variable that use number for its name, with GSON

后端 未结 4 1452
暗喜
暗喜 2021-01-16 12:06

First, im a beginner in GSON so please bear with me.

I tried to read a JSON from this url :

https://gdata.youtube.com/feeds/api/videos?author=radityad

4条回答
  •  长发绾君心
    2021-01-16 12:42

    You need define several classes first of all:

    MyGson

    public class MyGson {
    private String apiVersion;
    private Data data;
    
    public Data getData() {
        return data;
    }
    }
    

    Data

    public class Data {
    private String updated;
    private int totalItems = 0;
    private int startIndex = 0;
    private int itemsPerPage = 0;
    private  List items;
    
    public List getItems() {
        return items;
    }
    }
    

    Item

     public class Item {
    private String id;
    private String uploaded;
    private String updated;
    private String uploader;
    private String category;
    private String title;
    private String description;
    private Map  content;
    
    public Map getContent() {
        return content;
    }
    }
    

    Take a look, your content is map where key is 1,2,3,4,5,6 ....

    You can define Map content but since all your keys are integers..

    So now you can extract any value you want:

    Launcher

     ....
     Gson gson = new Gson();
    
        MyGson myGson = gson.fromJson(str, MyGson.class);
    
        List items = myGson.getData().getItems();
    
        if(items.size()>0){
            Item item = items.get(0);
    
            String myStr = item.getContent().get(1);
    
            System.out.println(myStr);
        }
    

    Output:

    rtsp://r6---sn-cg07lue6.c.youtube.com/CiILENy73wIaGQl1cubZZSUSXxMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp
    

提交回复
热议问题