3

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)

4 Answers 4

4

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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.

2 Comments

XurrencyResponse, lol, you are reading my mind. Same naming convention. I like that :-)
@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
0

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 :)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.