System.Text.Json.JsonSerializer.Serialize returns empty Json object “{}” [duplicate]

泄露秘密 提交于 2021-01-02 05:27:11

问题


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

回答1:


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

public int MyInt { get; set; }


来源:https://stackoverflow.com/questions/58784499/system-text-json-jsonserializer-serialize-returns-empty-json-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!