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);
}
Serialize(Object, Type, JsonSerializerOptions)Converts the value of a specified type into a JSON string.
The System.Text.Json namespace contains all the entry points and the main types. The System.Text.Json.Serialization namespace contains attributes and APIs for advanced scenarios and customization specific to serialization and deserialization.
JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).
Serialization and deserialization in . NET application, JSON data format conversion to . NET objects and vice versa is very common. Serialization is the process of converting . NET objects such as strings into a JSON format and deserialization is the process of converting JSON data into . NET objects.
im pretty sure the serializer doesn't work with fields. so use a property instead.
public int MyInt { get; set; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With