从API解析JSON数据(C#)
我目前正在以application/json数据的形式从web api获取信息。我遇到的问题是,有时使用JObject.Parse(response)会出现错误,而使用JArray.Parse(response)则不会出现错误,有时反之亦然。我已经四处寻找了一段时间,但还没有弄清楚为什么返回的一些数据周围有[],而有些则没有。也就是说,有没有一种方法可以一致地解析数据,不管数据周围是否有[]?目前我唯一能想到的是检查响应字符串是否以“[”开头,如果以“[”开头,则使用JArray.Parse,如果以“[”开头,则使用JObject.Parse,如果不以“[”开头,则使用JObject.Parse,但这似乎是一种丑陋的解决方案。我对API总体上还是相当陌生的,因此任何建议都将不胜感激 (编辑:语言为C#) 代码段:从API解析JSON数据(C#),c#,json,api,C#,Json,Api,我目前正在以application/json数据的形式从web api获取信息。我遇到的问题是,有时使用JObject.Parse(response)会出现错误,而使用JArray.Parse(response)则不会出现错误,有时反之亦然。我已经四处寻找了一段时间,但还没有弄清楚为什么返回的一些数据周围有[],而有些则没有。也就是说,有没有一种方法可以一致地解析数据,不管数据周围是否有[]?目前我唯一能想到的是检查响应字符串是否以“[”开头,如果以“[”开头,则使用JArray.Parse,如
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:
当我从服务器后端接收数据时,我使用
JSON.parse(response)
我假设你是用JaveScript写的
$.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
}
});
$.get(“/tictactoe/”+ID,{“thePosition”:curr\u line},函数(响应){
设x=JSON.parse(response);//这里x现在是一个JSON对象
对于(i=0;我很抱歉,这将是有用的添加我使用的语言。C)。谢谢你的回应,但是我认为C没有一个JSON.PARSER(),据我所知。试试这个,我会认为这是一个后端问题,不是一个一致的数据结构来自同一个API,他们应该解决它。
$.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
}
});