检测反序列化对象是否缺少 Json.NET 中 JsonConvert 类的字段

Detect if deserialized object is missing a field with the JsonConvert class in Json.NET(检测反序列化对象是否缺少 Json.NET 中 JsonConvert 类的字段)

本文介绍了检测反序列化对象是否缺少 Json.NET 中 JsonConvert 类的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Json.NET 反序列化一些 JSON 对象.然而,我发现,当我反序列化一个没有我要查找的属性的对象时,不会引发任何错误,但是当我访问它们时会为这些属性返回一个默认值.当我反序列化错误类型的对象时,我能够检测到这一点很重要.示例代码:

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());
        }
    }
}

这个程序的输出是:420

The output of this program is: 42 0

我宁愿抛出异常而不是静默失败.除此之外,有没有办法检测序列化是否找不到参数?

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 对象解析数据,然后使用键值查找检查参数,但我所在的代码库使用上面的模式,如果可能的话,我希望保持一致.

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 设置,您可以将其设置为 Error.(默认为 Ignore.)这将导致序列化程序在反序列化过程中遇到目标类中没有对应属性的 JSON 属性时抛出 JsonSerializationException.

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.

请参阅:MissingMemberHandling 设置.

这篇关于检测反序列化对象是否缺少 Json.NET 中 JsonConvert 类的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:检测反序列化对象是否缺少 Json.NET 中 JsonConvert 类的字段