Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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);
}
like image 869
MikeZ Avatar asked Nov 09 '19 23:11

MikeZ


People also ask

What does Jsonserializer serialize do?

Serialize(Object, Type, JsonSerializerOptions)Converts the value of a specified type into a JSON string.

What is System Text JSON?

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.

What is JSON and serialization?

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

What is Jsonserializer deserialize?

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.


1 Answers

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

public int MyInt { get; set; }
like image 70
Charles Avatar answered Sep 22 '22 17:09

Charles