Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert my variable Result to an object using JSONConvert?

I'm using .NET Core for Linux for a Console Program. Using Http functionality I'm get some information coming from a Webservice. Then I'm trying to cast the result to an object but I'm not able to use JSON.

I read this article but I don't find any example and I don't have access to JavaScriptSerializer

    public async void CallApi(Object stateInfo)
    {
        var client = new HttpClient();
        var requestContent = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("pair", "XETHZEUR"), });
        HttpResponseMessage response = await client.PostAsync("https://api.kraken.com/0/public/Trades", requestContent);
        HttpContent responseContent = response.Content;
        using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
        {
            String result = await reader.ReadToEndAsync();
            //Here I would like to do a deserialized of my variable result using JSON (JObject obj = (JObject)JsonConvert.DeserializeObject(result);) But I don't find any JSON object
        }
    }

EDIT I would like to know how can I use JSON to convert my variable result to an object like I do usually with c#:

        JObject obj = (JObject)JsonConvert.DeserializeObject(result);

I hope you will be able to help me.

Many thanks,

like image 885
eldondano Avatar asked Jun 29 '17 08:06

eldondano


1 Answers

You'll simply need some kind of dependency which is available for .NET core which can help you deserialize json.

Newtonsoft.Json is defacto standard and is available in .NET core in order to use it you have to add it into your project.json file

"dependencies" {
...
"Newtonsoft.Json": "10.0.3"
},

The appropriate using statement in your class

using Newtonsoft.Json

you can then deserialize using JsonConvert.DeserializeObject(json);

    public async void CallApi(Object stateInfo)
{
    var client = new HttpClient();
    var requestContent = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("pair", "XETHZEUR"), });
    HttpResponseMessage response = await client.PostAsync("https://api.kraken.com/0/public/Trades", requestContent);
    HttpContent responseContent = response.Content;
    using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
    {
        String result = await reader.ReadToEndAsync();
        //Here I would like to do a JSON Convert of my variable result
        var yourObject = JsonConvert.DeserializeObject(result);
    }
}
like image 84
pijemcolu Avatar answered Sep 19 '22 13:09

pijemcolu