檢測反序列化對象是否缺少Json.NET中JsonConvert類的字段我正在嘗試使用Json.NET反序列化一些JSON對象。但是我發(fā)現(xiàn),當我反序列化一個沒有我正在尋找的屬性的對象時,不會拋出任何錯誤,但是當我訪問它們時,會返回屬性的默認值。重要的是我能夠檢測到何時反序列化了錯誤類型的對象。示例代碼:using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using Newtonsoft.Json;namespace Json_Fail_Test{
class Program
{
[JsonObject(MemberSerialization.OptOut)]
private class MyJsonObjView
{
[JsonProperty("MyJsonInt")]
public int MyJsonInt { get; set; }
}
const string correctData = @"
{
'MyJsonInt': 42
}";
const string wrongData = @"
{
'SomeOtherProperty': 'fbe8c20b'
}";
static void Main(string[] args)
{
var goodObj = JsonConvert.DeserializeObject<MyJsonObjView>(correctData);
System.Console.Out.WriteLine(goodObj.MyJsonInt.ToString());
var badObj = JsonConvert.DeserializeObject<MyJsonObjView>(wrongData);
System.Console.Out.WriteLine(badObj.MyJsonInt.ToString());
}
}}該程序的輸出是:42 0我寧愿拋出一個例外來默默地失敗。沒有辦法檢測序列化是否找不到參數(shù)?我知道我可以使用Json對象解析數(shù)據(jù),然后使用鍵值查找檢查參數(shù),但我所使用的代碼庫使用上面的模式,如果可能,我希望保持一致。
3 回答

犯罪嫌疑人X
TA貢獻2080條經(jīng)驗 獲得超4個贊
將以下屬性放在必需的屬性上:
[DataMember(IsRequired = true)]
如果該成員不存在,則會拋出Newtonsoft.Json.JsonSerializationException。
正如Brian在下面建議的那樣,你的課堂上也需要這個屬性:
[DataContract]
- 3 回答
- 0 關(guān)注
- 902 瀏覽
添加回答
舉報
0/150
提交
取消