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

推荐答案

Net序列化程序的设置为MissingMemberHandling,您可以将其设置为Error.(默认值为Ignore.)这将导致序列化程序在反序列化期间每当遇到目标类中没有对应属性的JSON属性时抛出JsonSerializationException.

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

Result:

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

See: MissingMemberHandling setting.

Json相关问答推荐

Vega Lite中的图例对齐

Vegalite中分组条形图中的偏移量问题

当有2个嵌套数组时展平复杂的JSON

解析SQL中的嵌套JSON

nlohmann json:为什么我会得到一个解析错误?

使用 jq 重新格式化 JSON 输出

使用 Redis 作为键值存储

如何在 Apache NiFi 中使用 JoltTransformJson 删除流文件或具有空字段的整个对象?

阅读 JSON 正文 Firebase 云函数

Oracle Apex - 将 JSON 对象分配给变量以返回

将 js Array() 转换为 JSON 对象以用于 JQuery .ajax

如何从 JSON 对象中获取日期

如何使用 Swift 从 NSURLSession 获取 cookie?

在 Postgres 中向 JSON 对象添加元素

区分字符串和列表的 Pythonic 方式是什么?

将序列化表单的数据转换为 json 对象

通过 JSON 发送 HTML 代码

使用适用于 Python 的 Google API - 我从哪里获取 client_secrets.json 文件?

有没有一种快速的方法可以在文本编辑器中将 JavaScript 对象转换为有效的 JSON?

在播放框架 JsObject 中解析 Json 数组