Web Services 从响应中提取数据,Content.ReadStringASync

icomxhvb  于 2023-05-01  发布在  其他
关注(0)|答案(2)|浏览(114)

我正在尝试从Web服务中提取数据。我设法从使用HTTPClient的Web服务获得成功响应。但是,我无法提取特定值。例如,我的JSON文档读为
{"d":[{"__type":"Info:#website.Model","infoClosingHours":"06:00:00 PM","infoID":1,"infoOpeningDays":"Monday","infoOpeningHours":"09:00:00 AM","infoStatus":"Open"}]}
我想得到infoOpeningDays,但是我无法做到。
我试过用

dynamicObject.GetType().GetProperty("infoOpeningDays").GetValue(dynamicObject, null); 

dynamicObject["infoOpeningDays"];

但它一直给我空。
这是我的代码

private async void GetData(object sender, EventArgs e)
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("ip");

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

            try{
                HttpResponseMessage response = client.GetAsync("WebServices/information.svc/GetInformationJSON").Result;
                if (response.IsSuccessStatusCode)
                {
                    string jsonString = await response.Content.ReadAsStringAsync();
                    dynamic dynamicObject = JsonConvert.DeserializeObject(jsonString);
                    //string abc = dynamicObject.IEnumerator.[0].IEnumerator.[0].IEnumerator.[0].IEnumerator.[5].Name;
                    string abc = dynamicObject.GetType().GetProperty("infoOpeningDays").GetValue(dynamicObject, null);
                }
            }
            catch
            {

            }

        }
ne5o7dgx

ne5o7dgx1#

您应该直接从动态对象访问属性,如下所示:

dynamic dynamicObject = JsonConvert.DeserializeObject(json);
string infoClosingHours = dynamicObject.d[0].infoClosingHours;

或者这是一样的

string infoClosingHours = dynamicObject.d[0]["infoClosingHours"];
kyvafyod

kyvafyod2#

从Json提取所选属性

var json = await response.Content.ReadAsStringAsync();     
var result = JObject.Parse(json).SelectToken("createdDate").ToString();
// result will give the createdDate in string format.

相关问题