44

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

1 Answer 1

107

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

public int MyInt { get; set; }
Sign up to request clarification or add additional context in comments.

8 Comments

If this is the case, then why on earth is it not documented?
@stuartd - it is documented. See How to serialize and deserialize JSON in .NET: Serialization behavior: By default, all public properties are serialized. You can specify properties to exclude... Currently, fields are excluded.
@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”!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.