【发布时间】:2021-05-19 19:58:15
【问题描述】:
我目前正在从 web api 以 application/json 数据的形式获取信息。我遇到的问题是,有时我在使用 JObject.Parse(response) 时会出错,而在使用 JArray.Parse(response) 时却没有,有时反之亦然。我一直在四处寻找,但无法弄清楚为什么返回的某些数据有 [] 而有些则没有。话虽如此,有没有办法一致地解析数据,无论它是否有 [] ?我目前唯一能想到的是检查响应字符串是否以'['开头,如果是则使用JArray.Parse,如果不是则使用JObject.Parse,但这看起来有点难看解决方案。总的来说,我对 API 还是很陌生,所以任何建议都将不胜感激。
(编辑:语言是 C#)
代码片段:
using (WebClient webClient = new WebClient())
{
webClient.Headers.Add("Authorization", "Basic ***");
webClient.Headers.Add("clientId", clientId);
webClient.Headers.Add("Content-Type", "application/json");
string agreementResponse = webClient.DownloadString(urlAgreementBase + urlAgreementParams);
if (response == null)
{
throw new InvalidPluginExecutionException("Failed to retrieve company. Response was empty.");
}
var agreementObject = JArray.Parse(response);
}
JSON:
[
{
"id": int,
"name": "string",
"type": {
"id": int,
"name": "string",
"_info": {
"type_href": "url string"
}
},
"company": {
"id": int,
"identifier": "string",
"name": "string",
"_info": {
"company_href": "url string"
}
},
"contact": {
"id": int,
"name": "string",
"_info": {
"contact_href": "url string"
}
},
"site": {
"id": int,
"name": "string",
"_info": {
"site_href": "url string"
}
},
"location": {
"id": int,
"name": "string",
"_info": {
"location_href": "url string"
}
},
"department": {
"id": int,
"identifier": "string",
"name": "string",
"_info": {
"department_href": "url string"
}
},
"restrictLocationFlag": bool,
"restrictDepartmentFlag": bool,
"startDate": "date string",
"noEndingDateFlag": bool,
"cancelledFlag": bool,
"sla": {
"id": int,
"name": "string",
"_info": {
"sla_href": "url string"
}
}
}
]
【问题讨论】:
-
我认为这是一个后端问题,来自同一个 API 的数据结构不一致,他们应该解决它。