将JSON反序列化为相对类

时间:2018-03-01 09:16:06

标签: c# asp.net json json.net

我是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”: “费萨尔”, “操作”: “UPDATE”, “VoiceIAQStats”:{ “ID”:9 “esdId”:9 “esdName”: “费萨尔”}}]

2 个答案:

答案 0 :(得分:1)

您正在解析数组adn,因此您的所有数据都保存在数组的第一个元素中。您应该访问该数组的第一项,然后访问该属性,如下所示:

var firstElement = a[0];
var voiceIaqStats = firstElement["VoiceIAQStats"];

//Or in 1 line:
var voiceIaqStats = a[0]["VoiceIAQStats"];

答案 1 :(得分:0)

将结果作为对象会让您的生活更轻松。我会说尝试这样的事情。 (我自己没有测试过)

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