2017-10-16 149 views
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類的對象,但我試圖理解並模仿默認請求處理機制的行爲,當傳入的請求由控制器自動處理並反序列化員工對象

+2

改變你的'指定您的自定義轉換器實例LongId'到'ulong'' – Jonesopolis

+1

'LongId'需要一個數字而不是一個空字符串 – user12345

+1

'long'值應該對應於''LongId':「」'? – Sinatr

回答

0

問題是您的JSON對您的模型無效。

在第一種方法AddEmployee中,稱爲模型綁定的過程發生。 MVC完成將post內容轉換爲對象的工作。它似乎容忍類型不匹配,並原諒你的空字符串。

在第二種情況下,您嘗試自己做,並嘗試在不驗證輸入數據的情況下運行反序列化。 Newtonsoft JSON不理解空字符串和崩潰。

如果您仍然需要接受無效JSON,你可能希望通過實現自定義轉換器

public class NumberConverter : JsonConverter 
{ 
    public override bool CanWrite => false; 

    public override bool CanConvert(Type objectType) 
    { 
     return typeof(ulong) == objectType; 
    } 

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) 
    { 
     var value = reader.Value.ToString(); 

     ulong result; 
     if (string.IsNullOrEmpty(value) || !ulong.TryParse(value, out result)) 
     { 
      return default(ulong); 
     } 

     return result; 
    } 

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 
    { 
     throw new NotImplementedException(); 
    } 
} 

覆蓋默認的反序列化過程,然後調用反序列化時

return JsonConvert.DeserializeObject<Employee>(doc.ToJson(), new NumberConverter()); 
相關問題