【问题标题】:Consuming a nested JSON from a POST request, can't assign the nested JSON to my class从 POST 请求中使用嵌套的 JSON,无法将嵌套的 JSON 分配给我的班级
【发布时间】:2020-01-09 08:11:04
【问题描述】:

我有一个接收 JSON 字符串的 WebAPI 项目,它应该启动一个新对象并填充其值。我的课程如下所示:

    public class User
{
    public string email { get; set; }
    public string libraryId { get; set; }
    public string name { get; set; }
    public DateTime joiningDate { get; set; }
    public string zone { get; set; }
    public List<Rental> rental { get; set; }
}

    public class Rental
{
    public Dictionary<DateTime, int> rental;
}

我收到的 JSON 对象是这样的:

{
    "email": "a@b.ca",
    "libraryId": "314159",
    "name": "Jon Doe",
    "joiningDate": "12/31/9999 11:59:59 PM",
    "zone": "13",
    "Rental": 
        [
            {"12/31/1999 11:59:59 PM": 12}, 
            {"12/30/2999 11:59:59 PM": 13}
        ]
}

现在,为了验证对象是否正确填充,我在响应中将对象发回

    public HttpResponseMessage Post([FromBody]JObject incoming)
    {
        string toString = JsonConvert.SerializeObject(incoming);                
        User request = JsonConvert.DeserializeObject<User>(toString);     

        return Request.CreateResponse(HttpStatusCode.OK, request);
    }

嵌套的 JSON 总是如下所示:

    "Rental": [
    {
        "Rental": null
    },
    {
        "Rental": null
    }
]

我的问题是:我应该如何构建 Rental 类,以便可以使用 JSON 字符串中的输入正确填充它?我试图将出租字典保留在 User 类本身而不是它自己的类中,但它返回了一个错误。

【问题讨论】:

  • 写一个自定义的json转换器。在反序列化期间,传递自定义转换器。并让自定义转换器通过将值映射到 KeyValue 对来处理 Rental。
  • 更多关于自定义 Json 转换器的信息可以在这里找到:newtonsoft.com/json/help/html/CustomJsonConverter.htm

标签: c# json asp.net-web-api asp.net-web-api2


【解决方案1】:

Rental 类应如下所示:

public class Rental
{
    public KeyValuePair<DateTime, int> rental;
}

因为数组中的每个条目都是KeyValuePair&lt;DateTime, int&gt; 而不是Dictionary&lt;DateTime, int&gt;

另一种方法是将 json 的结构更改为:

{
    "email": "a@b.ca",
    "libraryId": "314159",
    "name": "Jon Doe",
    "joiningDate": "12/31/9999 11:59:59 PM",
    "zone": "13",
    "Rentals": 
     {
         "12/31/1999 11:59:59 PM": 12, 
         "12/30/2999 11:59:59 PM": 13
     }
}

然后上课:

public class User
{
    public string email { get; set; }
    public string libraryId { get; set; }
    public string name { get; set; }
    public DateTime joiningDate { get; set; }
    public string zone { get; set; }
    public Dictionary<DateTime, int> rentals {get;set;}
}

【讨论】:

  • 这会从数组中返回多个出租实例,如下所示: "rental":[{ "rental":{"key": "...", "Value":"... "}},{....}]。我想要做的是让它与输入相同,以DateTime 作为键,以int 作为其值
  • 我还给了你一个不同的方法。我认为与其使用 KeyValuePairs 数组,不如使用字典(如果可能的话)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多