您可以检测,如果你反序列化对象是缺少Json.NET与JsonConvert类中的字段如果你、您可以、字段、类中

2023-09-04 02:48:08 作者:上瘾

我想反序列化使用Json.NET一些JSON对象。我却发现,当我反序列化没有我要找的属性的对象不会引发错误了,但一个默认值返回的属性,当我访问他们。重要的是,我能够发现当我反序列化的错误类型的对象。例如:code:

I'm trying to deserialize some Json objects using Json.NET. I've found however that when I deserialize an object that doesn't have the properties I'm looking for that no error is thrown up but a default value is returned for the properties when I access them. It's important that I'm able to detect when I've deserialized the wrong type of object. Example code:

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

The output of this program is: 42 0

我会preFER一个异常被抛出来默默地失败。短的是有一种方法来检测,如果序列化没能找到一个参数?

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对象,然后检查是否有一个键值查找,但codeBase的我在参数使用上面的图案,我想保持这种一致性,如果有可能

I know I can parse the data with a Json object and then check for the parameter with a key value lookup but the codebase I'm in uses the pattern above and I'd like keep that consistent if it's possible.

推荐答案

该Json.Net串行器有一个 MissingMemberHandling 设置,你可以设置为错误。 (默认值为忽略)。这将导致序列化反序列化过程中抛出一个 JsonSerializationException 每当遇到一个JSON属性为此,有目标类中没有相应的属性。

The Json.Net serializer has a MissingMemberHandling setting which you can set to Error. (The default is Ignore.) This will cause the serializer to throw a JsonSerializationException during deserialization whenever it encounters a JSON property for which there is no corresponding property in the target class.

static void Main(string[] args)
{
    try
    {
        JsonSerializerSettings settings = new JsonSerializerSettings();
        settings.MissingMemberHandling = MissingMemberHandling.Error;

        var goodObj = JsonConvert.DeserializeObject<MyJsonObjView>(correctData, settings);
        System.Console.Out.WriteLine(goodObj.MyJsonInt.ToString());

        var badObj = JsonConvert.DeserializeObject<MyJsonObjView>(wrongData, settings);
        System.Console.Out.WriteLine(badObj.MyJsonInt.ToString());
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.GetType().Name + ": " + ex.Message);
    }
}

结果:

42
JsonSerializationException: Could not find member 'SomeOtherProperty' on object
of type 'MyJsonObjView'. Path 'SomeOtherProperty', line 3, position 33.