c# - 使用 .NET 4.0 任务模式使用 HTTPClient .ReadAsAsync 将

我正在尝试使用 .NET 4.0 任务模式反序列化从 http://api.usa.gov/jobs/search.json?query=nursing+jobs 返回的 JSON。它返回这个 JSON('Load JSON data' @ 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 方法的原因。

最佳答案

尝试使用 Json2csharp.com 网站之类的工具,而不是手动调整模型。粘贴在示例 JSON 响应中,越完整越好,然后拉入生成的生成类。至少,这会带走一些移动部件,让您在 csharp 中获得 JSON 的形状,让序列化器更轻松,并且您不必添加属性。

只要让它工作,然后修改你的类名,以符合你的命名约定,然后再添加属性。

编辑: 好的,经过一番折腾后,我成功地将结果反序列化为作业列表(我使用 Json2csharp.com 为我创建了类)

public class Job
{
        public string id { get; set; }
        public string position_title { get; set; }
        public string organization_name { get; set; }
        public string rate_interval_code { get; set; }
        public int minimum { get; set; }
        public int maximum { get; set; }
        public string start_date { get; set; }
        public string end_date { get; set; }
        public List<string> locations { get; set; }
        public string url { get; set; }
}

对您的代码进行编辑:

        List<Job> 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 jsonString = response.Content.ReadAsStringAsync();
              jsonString.Wait();
              model = JsonConvert.DeserializeObject<List<Job>>(jsonString.Result);

          });
        task.Wait();

这意味着您可以摆脱包含对象。值得注意的是,这不是与任务相关的问题,而是反序列化问题。

编辑2:

有一种方法可以获取 JSON 对象并在 Visual Studio 中生成类。只需复制选择的 JSON,然后编辑 > 选择性粘贴 > 将 JSON 粘贴为类。这里有一整页专门介绍这个:

http://blog.codeinside.eu/2014/09/08/Visual-Studio-2013-Paste-Special-JSON-And-Xml/

关于c# - 使用 .NET 4.0 任务模式使用 HTTPClient .ReadAsAsync 将 JSON 反序列化为数组或列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24131067/

相关文章:

security - JSONP 可以安全使用吗?

javascript - Angular 5 服务读取本地 .json 文件

c# - 如何将对象传递给 HttpClient.PostAsync 并序列化为 JSON 主体?

python - 将 Python namedtuple 序列化为 json

c# - 使用 ConfigurationBuilder 设置基本路径

javascript - 需要 Handlebars.js 来渲染对象数据而不是 "[Object

c# - 使用 JSON.net 获取 JToken 的名称/ key

javascript - 什么是 "top level JSON arrays",为什么它们存在安全

json - Groovy - 将对象转换为 JSON 字符串

json - 记录 JSON 结构的语法