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

后端 未结 6 1580
太阳男子
太阳男子 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:30

    Some times ago i decided this problem. I use DataContractJsonSerializer You will have __type in json, if your method for serialization have Base class parameter, but you give it subClass as parameter. More details:

    [DataContract]
    [KnownType(typeof(B))]
    public abstract class A
    {
        [DataMember]
        public String S { get; set; }
    }
    
    [DataContract]
    public class B : A
    {
        [DataMember]
        public Int32 Age { get; set; }
    }
    
    public static String ToJson(this T value)
    {
        var serializer = new DataContractJsonSerializer(typeof(T));
        using (var stream = new MemoryStream())
        {
            serializer.WriteObject(stream, value);
            return Encoding.UTF8.GetString(stream.ToArray());
        }
    }
    

    You have two methods for test:

    public static void ReadTypeDerived(A type)
    {
        Console.WriteLine(ToJson(type));
    }
    

    and

    public static void ReadType(T type)
    {
        Console.WriteLine(ToJson(type));
    }
    

    In first test you wiil have

    "{\"__type\":\"B:#ConsoleApplication1\",\"S\":\"Vv\",\"Age\":10}"

    In second:

    "{\"S\":\"Vv\",\"Age\":10}"

提交回复
热议问题