Jump to content
Sign in to follow this  
Guest sky.sanders

How do I use JsonClient to retrieve strongly typed data from a JSON API?

Recommended Posts

Guest sky.sanders

Please provide simple how-to code, using the platform of your choice, to fulfill the following use cases using the Stack Exchange API

Use Cases

1 – Simple parameter-less request:

The data looks like this:

{
  "api_sites": [
    {
      "name": "Stack Overflow",
      "logo_url": "http://sstatic.net/stackoverflow/img/logo.png",
      "api_endpoint": "http://api.stackoverflow.com",
      "site_url": "http://stackoverflow.com",
      "description": "Q&A for professional and enthusiast programmers",
      "icon_url": "http://sstatic.net/stackoverflow/img/apple-touch-icon.png",
      "aliases": [
        "http://www.stackoverflow.com"
      ],
      "state": "normal",
      "styling": {
        "link_color": "#0077CC",
        "tag_foreground_color": "#3E6D8E",
        "tag_background_color": "#E0EAF1"
      }
    },
    {
      "name": "Server Fault",
      "logo_url": "http://sstatic.net/serverfault/img/logo.png",
      "api_endpoint": "http://api.serverfault.com",
      "site_url": "http://serverfault.com",
      "description": "Q&A for system administrators and IT professionals",
      "icon_url": "http://sstatic.net/serverfault/img/apple-touch-icon.png",
      "state": "normal",
      "styling": {
        "link_color": "#10456A",
        "tag_foreground_color": "#444444",
        "tag_background_color": "#F3F1D9"
      }
    },

2 – Parameterized request

The data looks like this:

{
  "total": 412,
  "page": 1,
  "pagesize": 20,
  "users": [
    {
      "user_id": 8206,
      "user_type": "registered",
      "creation_date": 1221492246,
      "display_name": "Eli Bendersky",
      "reputation": 29557,
      "email_hash": "fc761ccaf6c0d7d977e2959f9bfebd06",
      "age": 30,
      "last_access_date": 1294053120,
      "website_url": "http://eli.thegreenplace.net",
      "location": "Israel",
      "about_me": "<p>Programmer and embedded engineer.</p>\r\n\r\n<p>\r\n<code>C, Python, VHDL, C++, Perl, Lisp, Scheme, Ruby</code>\r\n</p>\r\n",
      "question_count": 65,
      "answer_count": 877,
      "view_count": 1966,
      "up_vote_count": 1391,
      "down_vote_count": 175,
      "accept_rate": 92,
      "association_id": "3d8a0e33-a637-4d37-adfe-67dcc0833f24",
      "user_questions_url": "/users/8206/questions",
      "user_answers_url": "/users/8206/answers",
      "user_favorites_url": "/users/8206/favorites",
      "user_tags_url": "/users/8206/tags",
      "user_badges_url": "/users/8206/badges",
      "user_timeline_url": "/users/8206/timeline",
      "user_mentioned_url": "/users/8206/mentioned",
      "user_comments_url": "/users/8206/comments",
      "user_reputation_url": "/users/8206/reputation",
      "badge_counts": {
        "gold": 4,
        "silver": 52,
        "bronze": 120
      }
    },
    {
      "user_id": 123111,
      "user_type": "registered",
      "creation_date": 1245071966,
      "display_name": "Kirill V. Lyadvinsky",

Share this post


Link to post
Guest sky.sanders

C# – Parameterless

1 – Download the binaries or source to CityIndex.JsonClient fromhttps://github.com/cityindex/CIAPI.CS

2 – Add a reference to CityIndex.JsonClient.dll (or the source project) to your project

3 – Create classes that resemble the data that is returned from the API.

/// <summary>
/// A simple partial DTO that resembles the collection element returned from http://api.stackauth.com/1.0/sites
/// </summary>
private class Site
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("site_url")]
    public string SiteUrl { get; set; }

    [JsonProperty("api_endpoint")]
    public string ApiEndpoint { get; set; }

    [JsonProperty("description")]
    public string Description { get; set; }

}

/// <summary>
/// Simple collection wrapper that resembles the root json returned from  http://api.stackauth.com/1.0/sites
/// </summary>
private class SitesResponse
{
    [JsonProperty("api_sites")]
    public List<Site> Sites { get; set; }
}

4 – Retrieve the data

// creates a JSON client with nominal values for throttling and caching
var client = new Client(new Uri("http://stackauth.com/1.0"));

SitesResponse response = client.Request<SitesResponse>("sites", "GET");

foreach (Site site in response.Sites)
{
    Console.WriteLine("{0}\r\n\t{1}\r\n", site.Name, site.SiteUrl);
}

Share this post


Link to post
Guest sky.sanders

C# – Parameterized

1 – Download the binaries or source to CityIndex.JsonClient fromhttps://github.com/cityindex/CIAPI.CS

2 – Add a reference to CityIndex.JsonClient.dll (or the source project) to your project

3 – Create classes that resemble the data that is returned from the API.

///<summary>
/// A simple partial DTO that resembles the collection element returned from http://api.stackoverflow.com/1.0/users?filter=sky&page=1&pagesize=10
///</summary>
private class User
{
    [JsonProperty("user_id")]
    public int UserId { get; set; }

    [JsonProperty("reputation")]
    public int Reputation { get; set; }

    [JsonProperty("display_name")]
    public string DisplayName { get; set; }

    [JsonProperty("about_me")]
    public string AboutMe { get; set; }

    [JsonProperty("user_type")]
    public string UserType { get; set; }

}


/// <summary>
/// Simple collection wrapper that resembles the root json returned from  http://api.stackoverflow.com/1.0/users?filter=sky&page=1&pagesize=10
/// </summary>
private class UsersResponse
{
    [JsonProperty("total")]
    public int Total { get; set; }

    [JsonProperty("page")]
    public int Page { get; set; }

    [JsonProperty("pagesize")]
    public int PageSize { get; set; }

    [JsonProperty("users")]
    public List<User> Users { get; set; }
}

4 – Retrieve the data

// our target is http://api.stackoverflow.com/1.0/users?filter=sky&page=1&pagesize=10

// creates a JSON client with nominal values for throttling and caching
var client = new Client(new Uri("http://api.stackoverflow.com/1.0"));

string method = "GET";

string target = "users";


string uriTemplate = "?filter={filter}&page={page}&pagesize={pagesize}";

// each entry in the parameters dictionary will replace the template value
// of the same name. (template value = '{foo}')

Dictionary<string, object> parameters = new Dictionary<string, object>
    {
        { "filter", "sky" },
        { "page", 1 },
        { "pagesize", 10 },
    };

UsersResponse response = client.Request<UsersResponse>(target, uriTemplate, method, parameters);

foreach (User user in response.Users)
{
    Console.WriteLine("{0} - {1}", user.DisplayName, user.Reputation);
}

Share this post


Link to post

Here is a Java parameter-less version: (Warning! First draft. Not complete.)

DefaultJsonClient client = new DefaultJsonClient();
String url = "http://stackauth.com/1.0/sites";
SitesWrapper stats = (SitesWrapper)client.makeGetRequest(url, SitesWrapper.class);

Given classes:

public class SitesWrapper {
    private Site[] api_sites;
    public Site[] getSites() {
        return api_sites;
    }
}

and

public class Site {

    private String name;
    private String logo_url;
    private String api_endpoint;
    private String site_url;
    private String description;
    private String icon_url;
    private String[] aliases;
    private State state;
    private Styling styling;

    public String getName() {
        return name;
    }

    public String getLogo_url() {
        return logo_url;
    }

    public String getApi_endpoint() {
        return api_endpoint;
    }

    public String getSite_url() {
        return site_url;
    }

    public String getDescription() {
        return description;
    }

    public String getIcon_url() {
        return icon_url;
    }

    public String[] getAliases() {
        return aliases;
    }

    public State getState() {
        return state;
    }

    public Styling getStyling() {
        return styling;
    }

    public static enum State {
        normal, closed_beta, open_beta, linked_meta;
    }
}

and

public class Styling {
    private String link_color;
    private String tag_foreground_color;
    private String tag_background_color;

    public String getLink_color() {
        return link_color;
    }

    public String getTag_foreground_color() {
        return tag_foreground_color;
    }

    public String getTag_background_color() {
        return tag_background_color;
    }
}

Share this post


Link to post

 

C# – Parameterless

1 – Download the binaries or source to CityIndex.JsonClient fromhttps://github.com/cityindex/CIAPI.CS

2 – Add a reference to CityIndex.JsonClient.dll (or the source project) to your project

3 – Create classes that resemble the data that is returned from the API.

/// <summary>
/// A simple partial DTO that resembles the collection element returned from http://api.stackauth.com/1.0/sites
/// </summary>
private class Site
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("site_url")]
    public string SiteUrl { get; set; }

    [JsonProperty("api_endpoint")]
    public string ApiEndpoint { get; set; }

    [JsonProperty("description")]
    public string Description { get; set; }

}

/// <summary>
/// Simple collection wrapper that resembles the root json returned from  http://api.stackauth.com/1.0/sites
/// </summary>
private class SitesResponse
{
    [JsonProperty("api_sites")]
    public List<Site> Sites { get; set; }
}

4 – Retrieve the data

// creates a JSON client with nominal values for throttling and caching
var client = new Client(new Uri("http://stackauth.com/1.0"));

SitesResponse response = client.Request<SitesResponse>("sites", "GET");

foreach (Site site in response.Sites)
{
    Console.WriteLine("{0}\r\n\t{1}\r\n", site.Name, site.SiteUrl);
}
1

That looks like what I have so far on the Java side. C# generics are way better though.

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  
×