1
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.

ProGrammer
  • 55
  • 4
  • 2
    "This code returns {} which means that JsonSerializer.Serialize failed to do what it supposed to do" - no, it means that JsonSerializer hasn't done what you *expected* it to. I very much suspect it's because your code has a *field* and JsonSerializer deals in *properties*. Change your `JSONList` field to a property and I *suspect* it'll be fine. – Jon Skeet Oct 18 '21 at 14:58
  • @JonSkeet well thats unfortunate. But I'm going to keep this question here anyway, a few dozens of downvotes do not scare me. Thanks for help though, but now I need to figure out how to deserialize it without using names of properties for the list. But its different topic. – ProGrammer Oct 18 '21 at 15:02
  • Does this answer your question? [How to use class fields with System.Text.Json.JsonSerializer?](https://stackoverflow.com/questions/58139759/how-to-use-class-fields-with-system-text-json-jsonserializer) – Charlieface Oct 19 '21 at 00:31

1 Answers1

4

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194