Home > database >  Serialize custom type to JSON
Serialize custom type to JSON

Time:10-19

class Program
    {
        static void Main(string[] args)
        {
            JSONClass jsonClass = new JSONClass();
            JSONElement el = new JSONElement
            {
                A = 5,
                B = "test1"
            };
            JSONElement el2 = new JSONElement
            {
                A = 3,
                B = "test2"
            };
            jsonClass.JSONList.Add(el);
            jsonClass.JSONList.Add(el2);

            var output = JsonSerializer.Serialize<JSONClass>(jsonClass);
            Console.WriteLine(output);
        }
    }

    public class JSONClass
    {
        public List<JSONElement> JSONList = new List<JSONElement>();
    }

    public class JSONElement
    {
        public int A { get; set; }
        public string B { get; set; }
    }

This code returns {} which means that JsonSerializer.Serialize failed to do what it supposed to do. I imagine its because its not smart enough to handle custom types. And here is my question, how to do it. Internet is full of articles how to write custom converters etc, but none of them mention custom types.

CodePudding user response:

Your JSONList member is a public field - whereas JsonSerializer looks for properties.

Change your code for JSONClass to this:

public class JSONClass
{
    public List<JSONElement> JSONList { get; } = new List<JSONElement>();
}

The output is then:

{"JSONList":[{"A":5,"B":"test1"},{"A":3,"B":"test2"}]}

The bigger lesson to learn here is not to assume that the mistake is in the library you're using. Always start with an expectation that the problem is in your own code. Sometimes you'll find it really is in the library or system code (or in the compiler etc) but in my experience that's relatively rare.

  • Related