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

标签 c# json console .net-core

我将 .NET Core for Linux 用于控制台程序。 使用 Http 功能,我从 Web 服务中获得了一些信息。 然后我试图将结果转换为一个对象,但我无法使用 JSON。

我读了this article但我没有找到任何示例,而且我无权访问 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
        }
    }

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

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

我希望你能帮助我。

非常感谢,

最佳答案

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

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

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

类中适当的using语句

using Newtonsoft.Json

然后您可以使用 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);
    }
}

关于c# - 如何使用 JSONConvert 将变量 Result 转换为对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44820207/

相关文章:

c# - 在 Unity 中,是否可以从类型别名解析类型?

c# - 将日期时间字符串列表转换为日期时间值列表

c# - 删除已被 WPF 控件使用的图像

java - 如何检查 gson 的 int 字段是否为空? [安卓]

javascript - 如何知道何时从控制台调用 JavaScript 函数?

c# - 使用 Linq 的对象总和列表

javascript - 为什么我的函数不将 json 文件转换为数组 json

java - 在 Spring MVC 中重命名返回到 ResponseBody 的 JSON 对象

windows - 如何让我的控制台窗口出现在不同的位置?

C# 控制台?