Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON serialization missing properties in derived class

Tags:

json

c#

I am using Newtonsoft JSON serializer, and the serialized string is missing the properties from the derived class if the class is derived from a list. Here is my example code.

Classes:

[DataContract]
public class TestItem
{
    [DataMember]
    public int itemInt;
    [DataMember]
    public string itemString;

    public TestItem() {}
    public TestItem(int _intVal, string _stringVal)
    {
        itemInt = _intVal;
        itemString = _stringVal;
    }
}

[DataContract]
public class TestMain : List<TestItem>
{
    [DataMember]
    public int mainInt;
    [DataMember]
    public string mainString;
}

Serializing code:

string test;

// Test classes
TestMain main = new TestMain();
main.mainInt = 123;
main.mainString = "Hello";
main.Add(new TestItem(1, "First"));

test = Newtonsoft.Json.JsonConvert.SerializeObject(main);

After serialization, the value of test is:

[{\"itemInt\":1,\"itemString\":\"First\"}]

The values for mainInt and mainString are missing altogether.

The behaviour is not changed by the [DataContract] and [DataMember] tags, but I have them in there, to pre-empt the answer that they are missing.

How do I get JSON to recognize and serialize the mainInt and mainString properties of the derived class?

like image 384
user1961169 Avatar asked Nov 17 '15 04:11

user1961169


1 Answers

Is this what you want?

[DataContract]
public class TestItem
{
    [DataMember]
    public int itemInt { get; set; }
    [DataMember]
    public string itemString { get; set; }

    public TestItem() { }
    public TestItem(int _intVal, string _stringVal)
    {
        itemInt = _intVal;
        itemString = _stringVal;
    }
}

[DataContract]
public class TestMain
{
    [DataMember]
    public int mainInt { get; set; }
    [DataMember]
    public string mainString { get; set; }
    [DataMember]
    public List<TestItem> TestItem = new List<TestItem>();
}

class Program
{
    static void Main(string[] args)
    {
        string test;

        // Test classes
        TestMain main = new TestMain();
        main.mainInt = 123;
        main.mainString = "Hello";
        main.TestItem.Add(new TestItem(1, "First"));
        test = Newtonsoft.Json.JsonConvert.SerializeObject(main);
        Console.WriteLine(test);
    }
}
like image 148
MichaelMao Avatar answered Nov 09 '22 17:11

MichaelMao