简体   繁体   English

从 POST 请求中使用嵌套的 JSON,无法将嵌套的 JSON 分配给我的类

[英]Consuming a nested JSON from a POST request, can't assign the nested JSON to my class

I have a WebAPI project that recieves a JSON string, which should initiate a new object and fill its values.我有一个接收 JSON 字符串的 WebAPI 项目,它应该启动一个新对象并填充其值。 My classes look like this:我的课程是这样的:

    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;
}

and the JSON object I'm recieving is something like this:我收到的 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}
        ]
}

Now, to validate that the object is correctly populated, I send the object back in the response现在,为了验证对象是否正确填充,我在响应中将对象发送回

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

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

The nested JSON comes always looking like this:嵌套的 JSON 总是看起来像这样:

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

My question is: how should I build the Rental class so that I can properly populate it with the input from my JSON string?我的问题是:我应该如何构建 Rental 类,以便我可以使用来自我的 JSON 字符串的输入正确填充它? I tried to keep the Dictionary of rentals in the User class itself instead of its own class, but it returned an error.我试图将租赁字典保留在 User 类本身而不是它自己的类中,但它返回了一个错误。

The Rental class should look like: Rental类应如下所示:

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

Since each entry in the array is a KeyValuePair<DateTime, int> and not a Dictionary<DateTime, int> .由于数组中的每个条目都是KeyValuePair<DateTime, int>而不是Dictionary<DateTime, int>

A different approach would be to change the json's structure to:另一种方法是将 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
     }
}

And the class to:和班级:

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;}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM