简体   繁体   中英

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,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM