Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/grails/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用多态性将派生类序列化为JSON_C#_Json_Serialization_Polymorphism_System.text.json - Fatal编程技术网

C# 如何使用多态性将派生类序列化为JSON

C# 如何使用多态性将派生类序列化为JSON,c#,json,serialization,polymorphism,system.text.json,C#,Json,Serialization,Polymorphism,System.text.json,如果我有以下课程: 公共类父类 { 公共int ParentProperty{get;set;}=0; } 公共类子类:父类 { 公共字符串ChildProperty{get;set;}=“Child property”; } 公营货柜 { 公共双容器容量{get;set;}=0.2; 公共列表类容器{get;set;}=new List(); } 如果我在Program.cs中创建以下对象: //对象 var container=newcontainer(){ContainerCapacit

如果我有以下课程:

公共类父类
{
公共int ParentProperty{get;set;}=0;
}
公共类子类:父类
{
公共字符串ChildProperty{get;set;}=“Child property”;
}
公营货柜
{
公共双容器容量{get;set;}=0.2;
公共列表类容器{get;set;}=new List();
}
如果我在
Program.cs
中创建以下对象:

//对象
var container=newcontainer(){ContainerCapacity=3.14};
var parent=new ParentClass(){ParentProperty=5};
var child=new ChildClass(){ParentProperty=10,ChildProperty=“value”};
container.ClassContainer.Add(父级);
container.ClassContainer.Add(子级);
//系列化
var serializerOptions=new JsonSerializerOptions(){writeIndended=true};
var containerJson=JsonSerializer.Serialize(容器,serializerOptions);
Console.WriteLine(containerJson);
预期产出:

{
“集装箱容量”:3.14,
“类容器”:[
{
“父母财产”:5
},
{
“ChildProperty”:“值”,
“父母财产”:10
}
]
}
实际产量:

{
“集装箱容量”:3.14,
“类容器”:[
{
“父母财产”:5
},
{
“父母财产”:10
}
]
}

如何确保
child
上的属性
ChildProperty
也被序列化?对于接口多态性,我该怎么做呢?

我在网络上看到了关于这个问题的信息,似乎这不是很容易做到的。我建议使用
Newtonsoft.Json
library来解析对象,因为它是一个成熟的库,可以完美地处理子对象和父对象,而无需编写自定义设置

Newtonsoft.Json
安装nuget软件包,然后按如下方式对其进行解析:

var containerJson = JsonConvert.SerializeObject(container, Newtonsoft.Json.Formatting.Indented);
{
  "ContainerCapacity": 3.14,
  "ClassContainer": [
    {
      "ParentProperty": 5
    },
    {
      "ChildProperty": "value",
      "ParentProperty": 10
    }
  ]
}
其输出如下所示:

var containerJson = JsonConvert.SerializeObject(container, Newtonsoft.Json.Formatting.Indented);
{
  "ContainerCapacity": 3.14,
  "ClassContainer": [
    {
      "ParentProperty": 5
    },
    {
      "ChildProperty": "value",
      "ParentProperty": 10
    }
  ]
}

您只需要序列化,还是还需要反序列化?理想情况下,@dbcThen和。但如果您只需要序列化,请查看哪个更简单。事实上,这看起来像是部分或全部的复制品,同意吗?