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

问题描述 投票:0回答:1

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

    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": "[email protected]",
    "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类本身而不是其自己的类中,但是返回了错误。

c# json asp.net-web-api asp.net-web-api2
1个回答
1
投票

Rental类应该看起来像:

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

由于数组中的每个条目都是KeyValuePair<DateTime, int>,而不是Dictionary<DateTime, int>

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

{
    "email": "[email protected]",
    "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;}
}
© www.soinside.com 2019 - 2024. All rights reserved.