将JSON反序列化为相对类

问题描述 投票:0回答:2

我是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”}}]

c# asp.net json json.net
2个回答
1
投票

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

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

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

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());
                }
            }
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.