【发布时间】:2018-07-24 23:07:15
【问题描述】:
我的webapi方法是:
public JsonResult<List<MyClass>> PullData()
{
List<MyClass> data = new List<MyClass>();
data = db.TableName.Select(x => new MyClass
{
Id = x.Id,
IsActive = x.IsActive,
//other attribute..
}).ToList();
return Json(data);
}
我将这个 webapi 用作:
public async Task<string> Index()
{
string apiUrl = "http://localhost:90/api/Scheduler/pulldata";
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(apiUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(apiUrl);
if (response.IsSuccessStatusCode)
{
var data = await response.Content.ReadAsStringAsync();
JsonConvert.DeserializeXmlNode(data, "root"); //exception: XmlNodeConverter can only convert JSON that begins with an object.
}
}
return "Error";
}
我得到错误:
XmlNodeConverter 只能转换以对象开头的 JSON。
同样在 api 消费方法(即Index)中,当我调试并看到var data = await response.Content.ReadAsStringAsync(); 中的数据为JSON Visualizer 时,它显示数据正常。
更新 2:
这里是开始的部分json数据:
[{"LearningActivityKey":2122,"ModuleName":"certName","ModuleVersion":1.0,"ModuleDescription":"<p><span style=\"background-color:rgb(240, 240, 240); font-family:archivo narrow,helvetica,arial,sans-serif; font-size:16px; line-height:20px; white-space:pre-line\">Learn SAP
更新 3:
我已将 webapi 方法 PullData() 更改为只发送两条记录,以便我们可以轻松地查看问题是否与 json 数据有关。
完整的数据是:
[{"LearningActivityKey":2122,"ModuleName":"certName","ModuleVersion":0.0,"ModuleDescription":null,"BadgeName":null,"BadgeVersion":null,"BadgeDescription":null,"MozillaBadge":null,"LearningActivityName":null,"LearningActivityDescription":null,"StepName":null,"StepVersion":null,"StepDescription":null,"IsActive":false,"IsPublished":false,"CreatedDate":"0001-01-01T00:00:00","ModifiedDate":null},{"LearningActivityKey":2122,"ModuleName":"certName","ModuleVersion":0.0,"ModuleDescription":null,"BadgeName":null,"BadgeVersion":null,"BadgeDescription":null,"MozillaBadge":null,"LearningActivityName":null,"LearningActivityDescription":null,"StepName":null,"StepVersion":null,"StepDescription":null,"IsActive":false,"IsPublished":false,"CreatedDate":"0001-01-01T00:00:00","ModifiedDate":null}]
我在https://jsonformatter.curiousconcept.com/ 中粘贴了数据,上面写着:
而XML Visualizer 仍然没有显示任何数据。
【问题讨论】:
-
你也可以分享一下 JSON 吗?
-
@FaizanRabbani,请查看更新后的答案。让我知道我还能提供什么以更好地理解。
-
你应该试试 JsonConvert.DeserializeObject()
-
你能把json字符串的开头贴出来,这样我们就可以理解为什么它不是以对象开头的。可能是开头的空格或换行符。
-
@FaizanRabbani 我也试过
JsonConvert.DeserializeObject()。我收到错误:Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'MyClass' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.。 @jdweng 请查看更新的答案
标签: c# json xml asp.net-mvc asp.net-web-api