将JSON反序列化为相对类
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将JSON反序列化为相对类相关的知识,希望对你有一定的参考价值。
我是JSON和Web API的新手。我已经通过帮助书籍制作一个简单的控制台应用程序来获取URL响应,即JSON并使用NewtonSoft解析它。我无法从JSON访问VoiceIAQStats
部分数据。我在解析时需要帮助:
我的代码是:
async static void GetRequest(string url)
{
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(url))// .GetAsync(url))
{
using (HttpContent content = response.Content)
{
string mycontent = await content.ReadAsStringAsync();
//Console.WriteLine(mycontent);
JArray a = JArray.Parse(mycontent);
Console.WriteLine("Total Count is " + a.Count());
Console.WriteLine("Data is " + a.ToString());
}
}
}
}
JSON结果如下:
[{“id”:“faisal”,“operation”:“UPDATE”,“VoiceIAQStats”:{“id”:9,“esdId”:9,“esdName”:“faisal”}}]
答案
您将传递给数组,因此您的所有数据都保存在数组的第一个元素中。您应该访问该数组的第一项,然后访问该属性,如下所示:
var firstElement = a[0];
var voiceIaqStats = firstElement["VoiceIAQStats"];
//Or in 1 line:
var voiceIaqStats = a[0]["VoiceIAQStats"];
另一答案
将结果作为对象将使您的生活更轻松。我会说尝试这样的事情。 (我自己没有测试过)
private struct ResponseData
{
public List<Data> results { get; set; }
}
private struct Data
{
public string id { get; set; }
public string operation { get; set; }
public VoiceIA VoiceIAQStats { get; set; }
}
private struct VoiceIA
{
[JsonProperty("id")]
public long id { get; set; }
[JsonProperty("esdId")]
public long esdId { get; set; }
[JsonProperty("esdName")]
public string esdName { get; set; }
}
async static void GetRequest(string url)
{
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(url))// .GetAsync(url))
{
using (HttpContent content = response.Content)
{
var mycontent = content.ReadAsStringAsync();
ResponseData queryResponse = JsonConvert.DeserializeObject<ResponseData>(mycontent.Result);
string id = queryResponse.results[0].id;
int count = queryResponse.results.Count;
string operation = queryResponse.results[0].operation;
VoiceIA voiceObj = queryResponse.results[0].VoiceIAQStats;
long idOfVoice = voiceObj.id;
long esdId = voiceObj.esdId;
string esdName = voiceObj.esdName;
//// Console.WriteLine(mycontent);
//JArray a = JArray.Parse(mycontent);
//Console.WriteLine("Total Count is " + a.Count());
//Console.WriteLine("Data is " + a.ToString());
}
}
}
}
以上是关于将JSON反序列化为相对类的主要内容,如果未能解决你的问题,请参考以下文章