2013-05-06 47 views
0

我有2個相當複雜的對象,一個是解析成功,另一個是拋出異常。對象之間的唯一區別是2個雙重屬性。我反序列化作爲奇怪的Json.net異常「輸入字符串格式不正確。」

var item = JsonConvert.DeserializeObject<MyItem>(result.ToString()); 

MyItem擁有兩條線,所以在第一種情況下,他們應該是空的(項目不追究他們),並且在第二種情況下,他們應該被設置(因爲他們在JSON存在和反序列化對象)。

跟蹤:

at Newtonsoft.Json.Utilities.ConvertUtils.IntParseFast(Char[] value, Int32 start, Int32 length) 
at Newtonsoft.Json.JsonTextReader.ParseNumber() 
at Newtonsoft.Json.JsonTextReader.ParseValue() 
at Newtonsoft.Json.JsonTextReader.ReadInternal() 
at Newtonsoft.Json.JsonReader.ReadAsInt32Internal() 
at Newtonsoft.Json.JsonTextReader.ReadAsInt32() 
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter) 
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id) 
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue) 
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue) 

有什麼建議?

+4

請在每種情況下發布您正在解析的JSON('result.ToString()')。一個簡短但完整的例子將是理想的。 – 2013-05-06 12:06:35

+0

發佈'MyItem'類和兩個JSON字符串。 – ken2k 2013-05-06 12:07:06

+0

@JonSkeet聖潔的廢話,夥計們,我應該去賣一些漢堡包:)在複製diff部分時,我發現其中一個屬性設置爲int ... – 2013-05-06 12:12:58

回答

2

請根據複合對象的基本類型檢查序列化對象的格式。並且還使用這部分代碼

var item = JsonConvert.DeserializeObject<MyItem>(result.ToString(), 
new JsonSerializerSettings(){DefaultValueHandling = DefaultValueHandling.Ignore});