1 回答
TA貢獻(xiàn)1876條經(jīng)驗 獲得超6個贊
您的基本問題是您已聲明ErrorDTOas IEnumerator, IEnumerable,即無類型、非泛型可枚舉。Json.NET 將這樣的對象解釋為只讀的無類型集合,因此當(dāng)您嘗試填充它時,會出現(xiàn)異常:
System.ArgumentNullException: Value cannot be null.
at System.RuntimeType.MakeGenericType(Type[] instantiation)
at Newtonsoft.Json.Serialization.JsonArrayContract.CreateWrapper(Object list)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Populate(JsonReader reader, Object target)
at Newtonsoft.Json.JsonSerializer.PopulateInternal(JsonReader reader, Object target)
at Newtonsoft.Json.JsonConvert.PopulateObject(String value, Object target, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.PopulateObject(String value, Object target)
異常消息無用且具有誤導(dǎo)性,但真正的原因是 Json.NET 無法知道要反序列化到的集合項目的目標(biāo)類型,或者在反序列化后添加它們的方法,對于任何無類型,只讀集合。
解決此類問題的正常方法是聲明ErrorDTO為 anICollection<ErrorObj>并實現(xiàn)必要的泛型方法,從而將項目類型和Add()方法通知 Json.NET,但不幸的是,您聲明
我不能改變他們[類]。
因此,最簡單的解決方法是填充基礎(chǔ)列表:
Newtonsoft.Json.JsonConvert.PopulateObject(json, resultDTO.ErrorList);
演示小提琴在這里。
- 1 回答
- 0 關(guān)注
- 243 瀏覽
添加回答
舉報
