問題
在寫Webservices時,碰到的問題。
定義的類
public class User { public string sID { get; set; } public int? iAge { get; set; } public string sName { get; set; } }
(1)當iAge為非空值
string strJson = "{\"sID\": \"b52c5343-bb34-48ed-8820-ef21f33688a0\",\"iAge\": \"3\",\"sName\": \"LiLei\"}";
結果:正常解析。三個字段都有值。
(2)當iAge字段未傳遞時
string strJson = "{\"sID\": \"b52c5343-bb34-48ed-8820-ef21f33688a0\",\"sName\": \"LiLei\"}";
結果:正常解析。sID和sName有值,iAge字段為NULL。
(3)當iAge字段為空字符串時
string strJson = "{\"sID\": \"b52c5343-bb34-48ed-8820-ef21f33688a0\",\"iAge\": \"\",\"sName\": \"LiLei\"}";
結果:解析失敗。
提示:參數解析出錯!Could not convert string to integer: . Line 136, position 32.
(4)問題:
明明iAge字段為int?,是可以賦值為NULL的啊。
自己寫了個控制台進行測試,結果是以上的三種情況都能正常解析。
百思不得其解,於是請教大佬。
原因
大佬一語道破,Newtonsoft.Json版本的原因。
工作項目使用的是4.0.8,我創建的控制台項目使用的是9.0.1。
大佬給的說明,我是看不懂。我工作項目中使用的版本不支持轉換空的值類型吧。
於是,尋找版本:
地址:https://www.nuget.org/packages/Newtonsoft.Json/
使用的是 Newtonsoft.Json -Version 8.0.3 版本。
將工作項目中的dll文件進行了替換。
后續問題
替換后,就發布了一個版本。
然而,又報錯了。
原因:使用了更高版本的dll文件。
解決:
在web.config的<runtime></runtime>節點中,添加以下內容。
<dependentAssembly> <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-8.0.0.0" newVersion="8.0.0.0" /> </dependentAssembly>
至此完事。