gpt4 book ai didi

.net - 如何告诉 DataContractJsonSerializer 不包含 "__type"属性

转载 作者:行者123 更新时间:2023-12-02 03:17:54 25 4
gpt4 key购买 nike

我需要将 KnownType 添加到下面的代码中才能成功序列化。当我这样做时,生成的 JSON 如下:

JSON form of Adult with 1 child: {"age":42,"name":"John","children":[{"__type":"
Child:#TestJson","age":4,"name":"Jane","fingers":10}]}

如何让它不包含“__type”:“Child:#TestJson”?我们在某些查询中返回数百个这样的元素,并且额外的文本将会增加。

完整代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

namespace TestJson
{
class Program
{
static void Main(string[] args)
{
Adult parent = new Adult {name = "John", age = 42};

MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Adult));
ser.WriteObject(stream1, parent);

stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
Console.Write("JSON form of Adult with no children: ");
Console.WriteLine(sr.ReadToEnd());


Child child = new Child { name = "Jane", age = 4, fingers=10 };

stream1 = new MemoryStream();
ser = new DataContractJsonSerializer(typeof(Child));
ser.WriteObject(stream1, child);

stream1.Position = 0;
sr = new StreamReader(stream1);
Console.Write("JSON form of Child with no parent: ");
Console.WriteLine(sr.ReadToEnd());


// now connect the two
parent.children.Add(child);

stream1 = new MemoryStream();
ser = new DataContractJsonSerializer(typeof(Adult));
ser.WriteObject(stream1, parent);

stream1.Position = 0;
sr = new StreamReader(stream1);
Console.Write("JSON form of Adult with 1 child: ");
Console.WriteLine(sr.ReadToEnd());
}
}

[DataContract]
[KnownType(typeof(Adult))]
[KnownType(typeof(Child))]
class Person
{
[DataMember]
internal string name;

[DataMember]
internal int age;
}

[DataContract]
class Adult : Person
{
[DataMember]
internal List<Person> children = new List<Person>();
}

[DataContract]
class Child : Person
{
[DataMember]
internal int fingers;
}
}

最佳答案

正如我在上一个问题中告诉你的,我不知道,但一些研究使我相信以下内容可能会实现你想要的:

var settings = new DataContractJsonSerializerSettings();
settings.EmitTypeInformation = EmitTypeInformation.Never;

var serializer = new DataContractJsonSerializer(yourType, settings);

关于.net - 如何告诉 DataContractJsonSerializer 不包含 "__type"属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17815772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com