Missing JSON serialization properties in a derived class

I use the Newtonsoft JSON serializer, and the serialized string skips properties from the derived class if the class is derived from a list. Here is my sample 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 test value:

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

The values โ€‹โ€‹of mainInt and mainString are missing at all.

The behavior is not changed by the tags [DataContract] and [DataMember], but I am there to preempt the answer that they lack.

How to get JSON for recognizing and serializing properties of mainInt and mainString of a derived class?

+5
source share
3 answers

See how to put json attributes in your properties. Here is an example: Json.NET serial code with the root name . The only thing I am embarrassed to do is get the main conclusion from this list. This is not a recommended model or practice. add the list as another child property, and then extract from the list, json serialize gets confused with your intentions.

0
source

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); } } 
0
source

adding this attribute works for me:

using System.ComponentModel.DataAnnotations;

[Newtonsoft.Json.JsonObject (title = "root")] public class Testmain: List

0
source

Source: https://habr.com/ru/post/1236109/


All Articles