35

Environment: Visual Studio 2019 16.3.8, .NET 3.0.100, .NET Core 3.0 unit test.

All 3 calls below to System.Text.Json.JsonSerializer.Serialize return empty objects: "{}"

I must be doing something wrong ... but I just don't see it?

public class MyObj
{
    public int myInt;
}

[TestMethod]
public void SerializeTest()
{
    var myObj = new MyObj() { myInt = 99 };
    var txt1 = System.Text.Json.JsonSerializer.Serialize(myObj);
    var txt2 = System.Text.Json.JsonSerializer.Serialize(myObj, typeof(MyObj));
    var txt3 = System.Text.Json.JsonSerializer.Serialize<MyObj>(myObj);
}
MikeZ
  • 1,155
  • 1
  • 13
  • 20

1 Answers1

82

im pretty sure the serializer doesn't work with fields. so use a property instead.

public int MyInt { get; set; }
Charles
  • 2,721
  • 1
  • 9
  • 15
  • 8
    If this is the case, then why on earth is it [not documented](https://learn.microsoft.com/en-us/dotnet/api/system.text.json.jsonserializer.serialize?view=netcore-3.0)? – stuartd Nov 09 '19 at 23:50
  • 2
    Reference: [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) – stuartd Nov 09 '19 at 23:53
  • 2
    Also this issue - [JsonSerializer should support field as well as properties](https://github.com/dotnet/corefx/issues/36505) – stuartd Nov 09 '19 at 23:55
  • @stuartd i guess because fields are "officially" for internal things, if you want a public API its always via properties. See bindings on wpf and winforms etc. – Charles Nov 10 '19 at 00:03
  • Not serializing a public field is fine **if it is documented**. I used the new native Json support instead of Newtonsoft.Json for the first time this week in a scratch project, and it felt a bit weird. I won’t be using it again. – stuartd Nov 10 '19 at 01:11
  • 4
    @stuartd - it is documented. See [How to serialize and deserialize JSON in .NET: Serialization behavior](https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to#serialization-behavior): *By default, all public properties are serialized. You can specify properties to exclude... Currently, fields are excluded.* – dbc Nov 10 '19 at 03:43
  • 5
    @dbc “documented somewhere on the MS web site, which lets face it is a constantly shifting quicksand of information” is about 100 times less useful than “the behaviour of the method is documented in the method’s own documentation”! – stuartd Nov 10 '19 at 23:51
  • 1
    This is true for "Microsoft.AspNetCore.Mvc.Rendering.Serialize" as well. The code worked fine in Core 2.2. I am flabbergasted. Thank you for this answer. – Brandon Barkley Jun 26 '20 at 18:13