Search code examples
c#jsonattributesdatacontractserializerjson-deserialization

DataContractJsonSerializer - deserializing to non-attributed/inherited class


I would like to use the c# DataContractJsonSerializer to de-serialize some json into a type that lacks serialization attributes. This type also inherits from multiple interfaces with each interface having many public properties.

I cannot alter the type I am trying to de-serialize to, nor the interfaces from which it inherits - is what I'm trying to do possible in c#?


Solution

  • is what I'm trying to do possible in c#?

    All you have to do is writing a small piece of code to test.

    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(CL1));
    var m = new MemoryStream(Encoding.UTF8.GetBytes(@"{""I1"":""test1"",""I2"":""test2""}"));
    var cl1 = ser.ReadObject(m) as CL1; 
    Console.WriteLine(cl1.I1 + " " + cl1.I2);
    

    So the answer is YES

    public interface II1
    {
        string I1 { set; get; }
    }
    public interface II2
    {
        string I2 { set; get; }
    }
    public class CL1 : II1, II2
    {
        public string I1 { set; get; }
        public string I2 { set; get; }
    }