如何告诉DataContractJsonSerializer不包含“ __type”属性

问题描述

正如我在上一个问题中告诉您的那样,我不知道,但是一些研究使我相信以下内容可能会达到您想要的目标:

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

var serializer = new DataContractJsonSerializer(yourType, settings);

解决方法

我需要将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;
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...