我正在try 使用JSON反序列化一些JSON对象.网然而,我发现,当我反序列化一个没有我要查找的属性的对象时,不会抛出任何错误,但当我访问它们时,会为属性返回一个默认值.当我反序列化了错误类型的对象时,能够检测到这一点很重要.示例代码:
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());
}
}
}
该程序的输出为:
I would prefer an exception be thrown to failing silently. Short of that is there a way to detect if the serialization failed to find a parameter?
我知道我可以用Json对象解析数据,然后用键值查找判断参数,但我所在的代码库使用上述模式,如果可能的话,我希望保持一致.