Use json object in c #

http://xurrency.com/api this web service returns a json response message. how can I use this message as an object in my .net project (asp.net web application)

+3
source share
4 answers

You can start by defining the classes of models 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; }
}

After that, 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);
    }
}
+4
source

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

+1
source

System.Web.Extensions.dll using System.Web.Script.Serialization; () , JavaScriptSerializer - , JSON, `Deserialize, ..

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

:

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;}
}

serializer.Deserialize<XurrencyResponse>, serializer JavaScriptSerializer.

+1

Another alternative is using Json.NET

I used this when analyzing Json data and was very pleased with this library, since you do not need to model explicit classes for storing data if you analyze simple output and provide you with options if you need to analyze more complex results.

Check out this library before making your choice :)

0
source

Source: https://habr.com/ru/post/1767725/


All Articles