我将 .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/