【发布时间】:2014-06-10 00:27:49
【问题描述】:
我正在尝试使用 .NET 4.0 任务模式反序列化从 http://api.usa.gov/jobs/search.json?query=nursing+jobs 返回的 JSON。它返回这个 JSON('加载 JSON 数据'@http://jsonviewer.stack.hu/)。
[
{
"id": "usajobs:353400300",
"position_title": "Nurse",
"organization_name": "Indian Health Service",
"rate_interval_code": "PA",
"minimum": 42492,
"maximum": 61171,
"start_date": "2013-10-01",
"end_date": "2014-09-30",
"locations": [
"Gallup, NM"
],
"url": "https://www.usajobs.gov/GetJob/ViewDetails/353400300"
},
{
"id": "usajobs:359509200",
"position_title": "Nurse",
"organization_name": "Indian Health Service",
"rate_interval_code": "PA",
"minimum": 42913,
"maximum": 61775,
"start_date": "2014-01-16",
"end_date": "2014-12-31",
"locations": [
"Gallup, NM"
],
"url": "https://www.usajobs.gov/GetJob/ViewDetails/359509200"
},
...
]
索引操作:
public class HomeController : Controller
{
public ActionResult Index()
{
Jobs model = null;
var client = new HttpClient();
var task = client.GetAsync("http://api.usa.gov/jobs/search.json?query=nursing+jobs")
.ContinueWith((taskwithresponse) =>
{
var response = taskwithresponse.Result;
var jsonTask = response.Content.ReadAsAsync<Jobs>();
jsonTask.Wait();
model = jsonTask.Result;
});
task.Wait();
...
}
职位和职位类别:
[JsonArray]
public class Jobs { public List<Job> JSON; }
public class Job
{
[JsonProperty("organization_name")]
public string Organization { get; set; }
[JsonProperty("position_title")]
public string Title { get; set; }
}
当我在jsonTask.Wait(); 上设置断点并检查jsonTask 时,状态为
故障。 InnerException 是“类型 ProjectName.Jobs 不是一个集合。”
我从没有 JsonArray 属性的 Jobs 类型和作为数组 (Job[]) 的 Jobs 开始,得到了这个错误。
public class Jobs { public Job[] JSON; }
+ InnerException {"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'ProjectName.Models.Jobs' because the type requires a JSON object (e.g. {\"name\":\"value\"}) to deserialize correctly.\r\n
To fix this error either change the JSON to a JSON object (e.g. {\"name\":\"value\"}) or change the deserialized type to an array or a type that implements a collection interface
(e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.\r\n
Path '', line 1, position 1."} System.Exception {Newtonsoft.Json.JsonSerializationException}
如何使用 .NET 4.0 任务模式处理此站点的 JSON?在转向 .NET 4.5 中的 await async 模式之前,我想先完成这项工作。
答案更新:
这是一个使用 .NET 4.5 异步等待模式和 brumScouse 答案的示例。
public async Task<ActionResult>Index()
{
List<Job> model = null;
var client = newHttpClient();
// .NET 4.5 async await pattern
var task = await client.GetAsync(http://api.usa.gov/jobs/search.json?query=nursing+jobs);
var jsonString = await task.Content.ReadAsStringAsync();
model = JsonConvert.DeserializeObject<List<Job>>(jsonString);
returnView(model);
}
您需要引入System.Threading.Tasks 命名空间。
注意:.Content 上没有可用的.ReadAsString 方法,这就是我使用.ReadAsStringAsync 方法的原因。
【问题讨论】:
-
你试过
ReadAsAsync<Job[]>()吗? -
不起作用,在 taskwithresponse 的 .Result 上产生此错误。错误 1“System.Threading.Tasks.Task”不包含“Result”的定义,并且找不到接受“System.Threading.Tasks.Task”类型的第一个参数的扩展方法“Result”(您是否缺少使用指令还是程序集引用?)
-
这没有任何意义,改变
ReadAsAsync()中的类型并不能改变代码之前的行为方式。 -
不错。它嵌入在 ContinueWith 语句中。请创建一个新的 MVC4 应用程序(在 VS 2012 中工作)并粘贴到这个控制器和两个类中?你能复制错误吗?如果是这样,您能否建议一个经过测试的解决方案来解决问题?
标签: c# json asp.net-mvc-4 task-parallel-library dotnet-httpclient