1

I've been struggling for quite a while, but now I managed to successfully pull JSON data from a web API.

My code so far (only a test snippet thus far):

var url = "http://www.trola.si/bavarski";
string text;

HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = WebRequestMethods.Http.Get;
request.Accept = "application/json";

var json = (HttpWebResponse)request.GetResponse();


using (var sr = new StreamReader(json.GetResponseStream()))
{
    text = sr.ReadToEnd();
}

As far as pulling data goes, this is ok, right?

Well here's where it gets a bit confusing. There are a lot resources online and all of them differ quite a bit. Do I need to create a class that will hold the data and { get; set; } too?

Would RESTsharp or Json.NET make my job easier? Any suggestions are appreciated.

mythic
  • 763
  • 1
  • 8
  • 27
  • 1
    Possible duplicate of [How to Deserialize JSON data?](http://stackoverflow.com/questions/18242429/how-to-deserialize-json-data) – Bart Dec 22 '15 at 07:41

4 Answers4

3

You do not need any third party JSON libs.

  1. Get the data to a string. You have already done this.

  2. Create your data classes. I like igrali's idea of using Visual Studio to do it. But if the data is simple just write the class yourself:

        [DataContract]
        public class PersonInfo
        {
            [DataMember]
            public string FirstName { get; set; }
    
            [DataMember]
            public string LastName { get; set; }
        }
    
  3. Deserialize from the string to the classes:

I like to use this generic helper:

    public static T Deserialize<T>(string json)
    {
        using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            T obj = (T)serializer.ReadObject(stream);
            return obj;
        }
     }

And then call it like this:

            PersonInfo info = (PersonInfo)JsonHelper.Deserialize<PersonInfo>(s);
Jon
  • 2,861
  • 2
  • 15
  • 14
2

There's a WebApi client that will take care of all of the serialization for you.

http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client

Here's a sample:

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://localhost:9000/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    // New code:
    HttpResponseMessage response = await client.GetAsync("api/products/1");
    if (response.IsSuccessStatusCode)
    {
        Product product = await response.Content.ReadAsAsync<Product>();
        Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
    }
}
jrummell
  • 41,300
  • 17
  • 110
  • 165
2

First of all, you will want to create classes that represent the JSON model you received. There's more than one way to do it - you can use json2csharp or even better, the Visual Studio feature called Paste JSON As Classes (find it in: Edit -> Paste Special -> Paste JSON As Classes).

Once you have the classes, you can use Json.NET to help you with the JSON response. You probably want to deserialize the string (JSON) you received to C# objects. To do it, you can just call the JsonConvert.DeserializeObject method.

var myObject = JsonConvert.DeserializeObject<MyClass>(json);

where MyClass is any kind of type you are deserializing to.

Igor Ralic
  • 14,835
  • 4
  • 40
  • 50
2

Json.net helps a lot with this. You can deserialize to anonymous types or POCO objects. I hope below solution helps you get started.

async Task Main()
{
    using (var client = new HttpClient())
    {
        using (var request = new HttpRequestMessage())
        {
            request.RequestUri = new Uri("http://www.trola.si/bavarski");
            request.Headers.Accept.Add(new  MediaTypeWithQualityHeaderValue("application/json"));
            request.Method = HttpMethod.Get;
            var result = await client.SendAsync(request);
            string jsonStr = await result.Content.ReadAsStringAsync();
            Result obj = JsonConvert.DeserializeObject<Result>(jsonStr);
            obj.Dump();
        }
    }
}

// Define other methods and classes here
public class Result
{
    [JsonProperty(PropertyName = "stations")]
    public Station[] Stations { get; set;}
}

public class Station
{
    [JsonProperty(PropertyName = "number")]
    public string Number { get; set; }
    [JsonProperty(PropertyName = "name")]
    public string Name { get; set; }
    [JsonProperty(PropertyName = "buses")]
    public Bus[] Buses { get; set; }
}


public class Bus
{
    [JsonProperty(PropertyName = "direction")]
    public string Direction { get; set; }
    [JsonProperty(PropertyName = "number")]
    public string Number { get; set; }
    [JsonProperty(PropertyName = "arrivals")]
    public int[] Arrivals { get; set; }
}
loneshark99
  • 646
  • 4
  • 15