Search code examples
javaandroidjsongsonjson-c

How to read JSON-c data from Youtube API using GSON in Android Apps


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

I want to read the data that i retrieved from this link :

https://gdata.youtube.com/feeds/api/videos?author=radityadika&v=2&alt=jsonc

So i tried to create some classes that represent the result of the link above :

Video.java

public class Video implements Serializable {
    // The title of the video
    @SerializedName("title")
    private String title;
    // A link to the video on youtube
    @SerializedName("url")
    private String url;
    // A link to a still image of the youtube video
    @SerializedName("thumbUrl")
    private String thumbUrl;

    @SerializedName("id")
    private String id;

    public Video(String id, String title, String url, String thumbUrl) {
        super();
        this.id = id;
        this.title = title;
        this.url = url;
        this.thumbUrl = thumbUrl;
    }

    /**
     * @return the title of the video
     */
    public String getTitle(){
        return title;
    }

    /**
     * @return the url to this video on youtube
     */
    public String getUrl() {
        return url;
    }

    /**
     * @return the thumbUrl of a still image representation of this video
     */
    public String getThumbUrl() {
        return thumbUrl;
    }

    public String getId() {
        return id;
    }
}

Library.java

public class Library implements Serializable{
    // The username of the owner of the library
    @SerializedName("user")
    private String user;
    // A list of videos that the user owns
    private List<Video> videos;

    public Library(String user, List<Video> videos) {
        this.user = user;
        this.videos = videos;
    }

    /**
     * @return the user name
     */
    public String getUser() {
        return user;
    }

    /**
     * @return the videos
     */
    public List<Video> getVideos() {
        return videos;
    }
}

After that, i tried to retrieve the data using those code :

@Override
    public void run() {
        try {
            // Get a httpclient to talk to the internet
            HttpClient client = new DefaultHttpClient();
            // Perform a GET request to YouTube for a JSON list of all the videos by a specific user
            HttpUriRequest request = new HttpGet("https://gdata.youtube.com/feeds/api/videos?author="+username+"&v=2&alt=jsonc");
            //HttpUriRequest request = new HttpGet("https://gdata.youtube.com/feeds/api/videos?title="+username+"&v=2&alt=jsonc");
            // Get the response that YouTube sends back
            HttpResponse response = client.execute(request);
            // Convert this response into a readable string
            //String jsonString = StreamUtils.convertToString(response.getEntity().getContent());
            final int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) { 
                //Log.w(getClass().getSimpleName(), "Error " + statusCode);
            }
            // Create a JSON object that we can use from the String
            //JSONObject json = new JSONObject(jsonString);

            HttpEntity getResponseEntity = response.getEntity();
            InputStream httpResponseStream = getResponseEntity.getContent();
            Reader inputStreamReader = new InputStreamReader(httpResponseStream);

            Gson gson = new Gson();
            this.library = gson.fromJson(inputStreamReader, Library.class);


        } catch (Exception e) {
            Log.e("Feck", e);
        }
    }

However i cant retrieve the data. The this.library variable, which is an instance of Library Class always null.

Any help is appreciated, and please ask me if you need more code.

Thanks very much


Solution

  • OK, I can understand you do not have any idea about JSON and Gson... but have you taken at least a quick look to JSON specifications or Gson documentation?

    After reading just a little while, I suggest you to use this handy online JSON Viewer to view the JSON data you're retrieving in a user-friendly way. You just need to copy the whole JSON in the Text tab and click the Viewer tab...

    If you do that, you'll see the structure of your JSON, which is something like this:

    {
      ...
      "data": {
        ...
        "items": [
          {
            "id": "someid",
            "title": "sometitle",
            ...
          },
          ...
        ]
      }
    }
    

    Now, what you have to do is to create a Java class structure that represents the data structure of your JSON, and you are not doing it! Why did you add the attributes user and videos to your Library class? Did you think that Gson can magically understand that you want to retrieve the user and his videos? It doesn't really work like that......

    In order to create the suitable class structure, start by doing something like this (in pseudo-code):

    class Response
      Data data;
    
    class Data
      List<Item> items;
    
    class Item
      String id;
      String title;
    

    Because as you may have realized by now, this class structure does represent your JSON data! Then just add more classes and attributes depending on what data you want to retrieve (add only those classes and attributes you need to retrieve, the rest will be automatically skipped).