【发布时间】:2017-07-31 10:40:31
【问题描述】:
我有这个 HttpPost 方法:
[HttpPost]
public string Test([FromBody]List<Account> accounts)
{
var json = JsonConvert.SerializeObject(accounts);
Console.Write("success");
return json;
}
这是我的 Account 类:
public class Account
{
public int accountId;
public string accountName;
public string createdOn;
public string registrationNumber;
}
这是我用邮递员发送的 json 文件:
{
"Account": [
{
"accountId": "1",
"accountName": "A purple door",
"createdOn": "25-07-2017",
"registrationNumber": "purple"
},
{
"accountId": "2",
"accountName": "A red door",
"createdOn": "26-07-2017",
"registrationNumber": "red"
},
{
"accountId": "3",
"accountName": "A green door",
"createdOn": "27-07-2017",
"registrationNumber": "green"
},
{
"accountId": "4",
"accountName": "A yellow door",
"createdOn": "25-07-2017",
"registrationNumber": "yellow"
}
]
}
如果我发送这个 json 我的方法不起作用,它会返回一个空对象。 使其工作的唯一方法是仅发送没有“帐户”的对象,如下所示:
[
{
"accountId": "1",
"accountName": "A purple door",
"createdOn": "25-07-2017",
"registrationNumber": "purple"
},
{
"accountId": "2",
"accountName": "A red door",
"createdOn": "26-07-2017",
"registrationNumber": "red"
},
{
"accountId": "3",
"accountName": "A green door",
"createdOn": "27-07-2017",
"registrationNumber": "green"
},
{
"accountId": "4",
"accountName": "A yellow door",
"createdOn": "25-07-2017",
"registrationNumber": "yellow"
}
]
但我想要以前的文件格式。 我的方法怎么能接收到之前的 JSON 呢?
【问题讨论】:
-
在具有 Account 类型的新类中创建一个复杂类型属性。
-
您尝试反序列化的参数类型与存储在 JSON 中的结构不对应。您可以使用 json2csharp.com 之类的东西来检查正确的 C# 类型是什么样的。
-
好吧,我已经尝试创建另一个类,其中包含我的 Account 类的列表,但尽管它返回了正确数量的帐户,但它们每个都有空成员。
-
尝试添加为属性 {get;set;}