Platinum Partner
java,architects,enterprise-integration,javascript,pojo,json,tips and tricks

Using Square Retrofit REST Client with POJO

Another helpful resource when using Retrofit, JSON to POJO

In your maven pom.xml.

<dependency>
<groupId>com.squareup.retrofit</groupId>
<artifactId>retrofit</artifactId>
<version>(insert latest version)</version>
</dependency>
package com.agilemobiledeveloper.dataradiator.dao;
import retrofit.http.GET;
import retrofit.http.Path;
import retrofit.RestAdapter;
/**
 * 
 * @author spannt
 *
 */
public class TestGitHub {
 static final String API_URL = "https://api.github.com";
static class GithubUserData{
 String avatar_url;
 String bio;
 String blog;
 String company;
 String created_at;
 String email;
 String events_url;
 Number followers;
 String followers_url;
 Number following;
 String following_url;
 String gists_url;
 String gravatar_id;
 boolean hireable;
 String html_url;
 Number id;
 String location;
 String login;
 String name;
 String organizations_url;
 Number public_gists;
 Number public_repos;
 String received_events_url;
 String repos_url;
 String starred_url;
 String subscriptions_url;
 String type;
 String updated_at;
 String url;
 }
interface GithubUser {
 @GET("/users/{username}")
 GithubUserData user(@Path("username") String username);
 }
/**
 * 
 * @param args
 */
 public static void main(String... args) {
 // Create a very simple REST adapter which points the GitHub API endpoint.
 RestAdapter restAdapter = new RestAdapter.Builder()
 .setServer(API_URL)
 .build();

 // Create an instance of our GitHub API interface.
 GithubUser githubUser = restAdapter.create(GithubUser.class);
 GithubUserData userdata = githubUser.user("nxbdi");

 System.out.println("UserData=" + userdata.bio + "," + userdata.email + "," + userdata.name +
 userdata.location + "," + userdata.public_repos + "," + userdata.followers);
 }
}

The library is really simple to use especially if you create your POJO class with the JSONGen.

Console Output:

UserData=Java, Android, NoSQL, SQL. 20 years experience. MS/BS in Com Sci.,tim@agilemobiledeveloper.com,Tim SpannNew Jersey,205,22





Published at DZone with permission of {{ articles[0].authors[0].realName }}, DZone MVB. (source)

Opinions expressed by DZone contributors are their own.

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}