我目前正在尝试从我的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
{
}
}
答案 0 :(得分:0)
您应该直接从动态对象访问属性,如下所示:
dynamic dynamicObject = JsonConvert.DeserializeObject(json);
string infoClosingHours = dynamicObject.d[0].infoClosingHours;
或者这是相同的
string infoClosingHours = dynamicObject.d[0]["infoClosingHours"];