How to serialize class type but not the namespace to a Json string using DataContractJsonSerializer

后端 未结 6 1559
太阳男子
太阳男子 2021-02-05 21:17

I\'m trying to serialize a class hierarchy to a Json string using DataContractJsonSerializer, in a WCF service. the default behaviour for serializing a derived clas

6条回答
  •  隐瞒了意图╮
    2021-02-05 21:43

    Cheeso's answer was excellent. I did discover a refinement to cleaning up the __type field though:

    Rather than removing your subclass from its namespace you can add a property like the following:

    [DataMember(Name = "__type")]
    public string SubclassType
    {
        get
        {
            return "Subscriber";
        }
        set { }
    }
    

    You still get stuck with the ugly name "__type" but I found that because I was returning a list of subtypes I wanted to specify the type name anyway. You could even return a value of "" to further reduce response size. You could also just declare the property as:

    public string __type
    

    but I found that to accentuate the hack so I stuck with an appropriate property name and then renamed it.

    -Joey

提交回复
热议问题