如何使用JSONConvert将变量Result转换为对象?

eld*_*ano 6 c# console json .net-core

我正在使用.NET Core for Linux进行控制台程序.使用Http功能我可以从Web服务获得一些信息.然后我试图将结果转换为对象,但我无法使用JSON.

我读过这篇文章,但是我没有找到任何示例,也没有访问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
        }
    }
Run Code Online (Sandbox Code Playgroud)

编辑 我想知道如何使用JSON将我的变量结果转换为像我通常用c#那样的对象:

        JObject obj = (JObject)JsonConvert.DeserializeObject(result);
Run Code Online (Sandbox Code Playgroud)

我希望你能帮助我.

非常感谢,

pij*_*olu 1

您只需要某种可用于 .NET core 的依赖项,它可以帮助您反序列化 json。

Newtonsoft.Json 是事实上的标准,并且在 .NET core 中可用,为了使用它,您必须将其添加到您的 project.json 文件中

"dependencies" {
...
"Newtonsoft.Json": "10.0.3"
},
Run Code Online (Sandbox Code Playgroud)

类中适当的 using 语句

using Newtonsoft.Json
Run Code Online (Sandbox Code Playgroud)

然后你可以使用反序列化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);
    }
}
Run Code Online (Sandbox Code Playgroud)