views:

207

answers:

4

http://xurrency.com/api this webservice is returning a json response message. how can I use this message as an object in my .net project (asp.net web app)

+1  A: 

You need to deserialize the JSON data into an object before you can use it.

hmemcpy
+4  A: 

You could start by defining the model classes that will handle the response:

public class XurrencyResponse
{
    public string Status { get; set; }
    public string Code { get; set; }
    public string Message { get; set; }
    public Result Result { get; set; }
}

public class Result
{
    public decimal Value { get; set; }
    public string Target { get; set; }
    public string Base { get; set; }
    public DateTime Updated_At { get; set; }
}

Once you have them you simply call the service:

class Program
{
    static void Main()
    {
        var serializer = new JavaScriptSerializer();
        string json = null;
        using (var client = new WebClient())
        {
            json = client.DownloadString("http://xurrency.com/api/eur/gbp/1.5");
        }
        var response = serializer.Deserialize<XurrencyResponse>(json);
        Console.WriteLine(response.Status);
    }
}
Darin Dimitrov
+1  A: 

If you reference System.Web.Extensions.dll and add a using System.Web.Script.Serialization; directive to the top of the necessary code file(s), then you should have access to JavaScriptSerializer - then you simply create a class that looks like the JSON and call `Deserialize, i.e. for

{"result":{"updated_at":"2010-10-02T02:06:00Z", "value":1.3014,"target":"gbp","base":"eur"}, "code":0, "status":"ok"}

You might have:

public class XurrencyResponse {
    public class Result {
        public string updated_at {get;set;}
        public decimal value {get;set;}
        public string target {get;set;}
        public string base {get;set;}
    }
    public Result result {get;set;}
    public int code {get;set;}
    public string status {get;set;}
}

Then call serializer.Deserialize<XurrencyResponse>, where serializer is a JavaScriptSerializer instance.

Marc Gravell
@Marc, `XurrencyResponse`, lol, you are reading my mind. Same naming convention. I like that :-)
Darin Dimitrov
@Darin - I don't know why, but I do prefer nested types for my JSON DTOs. I originally named it "...Result", but *in this case* it is ambiguous with the inner `Result`
Marc Gravell
A: 

Another alternative is using Json.NET

I have been using this when parsing Json data, and have been very pleased with this library, since you don't need to model explicit classes to hold the data if you are parsing simple output, and gives you advances features if you need to parse more complicated output.

Check out this library before you make your choice :)

Øyvind Bråthen