What is the purpose of [Serializable], entities can be serialized without this feature.
public class NotSerializableModel
{
public int Id { get; set; }
public string? Name { get; set; }
public DateTime CreateTime { get; set; }
}
[Serializable]
public class SerializableModel
{
public int Id { get; set; }
public string? Name { get; set; }
public DateTime CreateTime { get; set; }
}
[Fact]
public async void SerializableTest()
{
var serModel = new SerializableModel()
{
Id = 1,
Name = "Test",
CreateTime = DateTime.Now,
};
var noSerModel = new NotSerializableModel()
{
Id = serModel.Id,
Name = serModel.Name,
CreateTime = serModel.CreateTime,
};
var serJson = System.Text.Json.JsonSerializer.Serialize(serModel);
var noSerJson = System.Text.Json.JsonSerializer.Serialize(noSerModel);
Assert.Equal(serJson, noSerJson);
Console.WriteLine(serJson);
}
When must I use this feature.
I can’t find any more instructions now, Google is saying, this means that you can serialize?
2
Answers
The [Serializable] attribute applies to binary and XML serialization, not JSON.
https://learn.microsoft.com/en-us/dotnet/api/system.serializableattribute?view=net-7.0
Yes of course the entities can be serialized without explicitly decorating the class as Serializable, but it helps the developers and the tools that are available in the IDEs to understand and figure out that the classes are designed for serialization purpose. So that the IDE is able to provide documentation and tips regarding that class.