0
我在閱讀可用職位後發佈此問題。我有一個ASP.NET web api控制器和以下方法。json字符串反序列化爲自定義對象
[DataContract]
public class CustomPerson
{
[DataMember]
public ulong LongId { get; set; }
}
[DataContract]
public class Employee : CustomPerson
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Address { get; set; }
}
在控制器
public class CustomController : ApiController
{
[HttpPost]
[ActionName("AddEmployee")]
public bool AddEmployee(Employee empInfo)
{
bool bIsSuccess = false;
// Code loginc here
bIsSuccess = true;
return bIsSuccess;
}
[HttpPost]
[ActionName("AddEmployeeCustom")]
public async Task<bool> AddEmployeeCustom()
{
string rawRequest = await Request.Content.ReadAsStringAsync();
bool bIsSuccess = false;
// Code loginc here
try
{
Employee emp = JsonConvert.DeserializeObject<Employee>(rawRequest);
}
catch (Exception ex)
{ }
return bIsSuccess;
}
}
當我調用下面的請求經由肥皂AddEmployee
然後UI即用於LongId空值將被忽略
{
"Name": "test1",
"Address": "Street 1",
"LongId": ""
}
無錯誤接收自定義對象
當我調用AddEmployeeCustom方法時,運行時會拋出異常:
Error converting value "" to type 'System.UInt64'. Path 'LongId', line 4, position 14.
我讀的一個選擇是將傳入的字符串轉換爲JObject,然後創建Employee類的對象,但我試圖理解並模仿默認請求處理機制的行爲,當傳入的請求由控制器自動處理並反序列化員工對象
改變你的'指定您的自定義轉換器實例LongId'到'ulong'' – Jonesopolis
'LongId'需要一個數字而不是一個空字符串 – user12345
'long'值應該對應於''LongId':「」'? – Sinatr