2017-07-31 57 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) 
    { 

    }