Newtonsoft JSON 序列化 - 如何展平引用类型字段

问题描述

我有一个类 (MyClass),其中有一个引用类型字段(我们称之为 MyNestedClass)。 我正在使用 Newtonsoft,我想序列化这个类,包括这个字段。但不是在 Json(一个 Json 对象)中“打开一个新块”,我希望这个字段与这个类的其他(原始)字段保持在同一级别。可以保证,MyNestedClass 只包含一个字段。

    public class MyClass
    {
        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("nested_prop",Required = Required.Always)]
        public MyNestedClass NestedProp { get; set; }

        ...
    }
    public class MyNestedClass
    {
        public string Address { get; set; }
    }

输出(带有一些值):

{
    "name" : "foo_val","nested_prop" : {
        "Address" : "bar_val"            // it gets its name (Address) by default (based on the prop name)
    }
}

我想要的:

{
    "name" : "foo_val","address" :  "bar_val"
}

(当然我有我的理由为什么我需要一个单独的类(MyNestedClass)而不是将该字符串(Address)放入 MyClass 类中)

我尝试通过覆盖 CustomCreationConverter 方法创建转换器 (WriteJson),但它在序列化过程中从未被调用...

================================================ =

编辑:

我使用 CustomCreationConverter 是因为我已经覆盖了它的 Create 方法(我真正问题中的 prop 类型是一个接口,而不是具体的类)

正如@dbc 所暗示的,WriteJson 没有被调用,因为在 CustomCreationConverter 中,CanWrite 方法被 return false 覆盖。在我的自定义转换器中也覆盖此方法可解决此问题。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...