2017-07-31 54 views
0

我有这样的HttpPost方法:C#HTTP POST接收JSON从身体

[HttpPost]  
public string Test([FromBody]List<Account> accounts) 
{ 
    var json = JsonConvert.SerializeObject(accounts); 
    Console.Write("success"); 
    return json; 
} 

,这是我的帐号等级:

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?

+0

与帐户类型创建新类的复杂类型属性。 –

+0

您试图反序列化的参数的类型与存储在JSON中的结构不对应。你可以使用像http://json2csharp.com/这样的东西来检查正确的C#类型是什么样的。 – kiziu

+0

嗯,我已经试图做出另一个类,其中包含我的帐户类的列表,但虽然它返回了正确数量的帐户,他们每个都有空成员。 – kostasandre

回答

1

尝试使用此合约来达到您的要求。

public class Rootobject 
{ 
    public Account[] Account { get; set; } 
} 

public class Account 
{ 
    public string accountId { get; set; } 
    public string accountName { get; set; } 
    public string createdOn { get; set; } 
    public string registrationNumber { get; set; } 
} 

方法应该是这样的。

[HttpPost]  
public string Test([FromBody]Rootobject accounts) 
{ 
    var json = JsonConvert.SerializeObject(accounts); 
    Console.Write("success"); 
    return json; 
} 
+1

谢谢它的工作......!我的糟糕之处在于我在Root对象中创建了一个帐户列表,而不是Array.Thanks – kostasandre

1

添加的包装为你的类账户和更改方法认定中

public class Account 
     { 
      public int accountId; 
      public string accountName; 
      public string createdOn; 
      public string registrationNumber; 
     } 
     public class AccountWrapper 
     { 
      public List<Account> Accounts { get; set; } 
     } 
public string Test([FromBody]AccountWrapper accounts) 
    { 

    }