[英]Parsing JSON data from API (C#)
我目前正在以应用程序/json 数据的形式从 web api 获取信息。 我遇到的问题是,有时我使用 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"
}
}
}
]
当我从服务器后端接收数据时,我使用JSON.parse(response)
我假设您正在使用 JaveScript 编写。 这是我为我的 webapp 编写的示例;
$.get("/tictactoe/" + ID, {"thePosition": curr_line}, function(response){
let x = JSON.parse(response); //here x is now a JSON object
for(let i = 0; i <= 2; i++){
for(let j = 0; j <= 4; j++){
console.log(x.gb[i][j]); //x holds a 2D-array called gb,
//you can access it with x["gb"] or x.gb then its corresponding elements with [][]
}
}
console.log(x["isValid"]); //isValid is the key, the value is a boolean true/false
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.