我正在使用ASP.NET MVC应用程序进行Web API调用(GET请求)来获取JSON数据。我能够检索数据但是当它返回时,JSON数据中现在有反斜杠。
C#Controller:
[HttpGet]
[Route("company-info/companyinfogetapidata")]
public ActionResult CompanyInfoGetApiData(string name, int CompanyCode, string city, string state, int zip)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("URL_BASE");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var request = client.GetAsync("URL_PATH");
return Json(request.Result.Content.ReadAsStringAsync().Result, JsonRequestBehavior.AllowGet);
}
当我使用Stackify Prefix查看从服务器返回的响应时,我得到的JSON数据如下所示:
"{\n\"results\":[\n{\n\t\"name\":\"Company XYZ\",\n\t\"providerName\": \"Company Provider Info\",
它应该是这样的:
{"results":[{"name":"Company XYZ", "providerName": "Company Provider Info",
最初我只是使用反斜杠,但我想要删除它们的原因是因为当我尝试在AJAX Success函数中使用此返回的数据时,JSON数据属性未被正确读取。当我尝试从foreach循环中访问Cannot read property '0' of undefined
时,出现name
错误。
AJAX代码:
$.ajax({
type: "GET",
url:"../companyfindergetapidata",
dataType: "json",
data: {DATA_HERE},
error:function(e){alert("nope"+e);},
success: function (xhr_request) {
var fetched_data = xhr_request["results"];
var i;
var iLength = xhr_request.length;
for (i = 0; i < iLength; i++) {
// THIS IS WHERE I GET AN ERROR "Cannot read property '0' of undefined
$("#CompanyFinderResultsContainer").append("<p>Name: " + fetched_data[i].name + "</p>");
}
}
});
非常感谢任何帮助!
答案 0 :(得分:1)
有些编辑,这更接近原始代码。注意添加使用;
using Newtonsoft.Json.Linq;
[HttpGet]
[Route("company-info/companyinfogetapidata")]
[AllowAnonymous]
public ActionResult CompanyInfoGetApiData(string name, int CompanyCode, string city, string state, int zip)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("URL_BASE");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var request = client.GetAsync("URL_PATH");
var json = request.Result.Content.ReadAsStringAsync().Result;
json = JToken.Parse(json).ToString();
return Json(json, JsonRequestBehavior.AllowGet);
}