-
Notifications
You must be signed in to change notification settings - Fork 5.4k
.NET 5.0 System.Text.Json Serialize/Deserialize throw exception #45221
Copy link
Copy link
Closed
Labels
Description
Here is class and extend function
// class
public class Res
{
public int Code { get; set; }
public string Msg { get; set; }
public Res(int code = 200, string msg = "Success")
{
Code = code;
Msg = msg;
}
}
public class Res<T> : Res
{
public T Body { get; set; }
public Res(T body = default, int code = 200, string msg = "Success")
: base(code, msg)
{
Body = body;
}
}
// Extend function ToJson()
public static class Ext
{
private static readonly JsonSerializerOptions _opts;
static Ext()
{
_opts = new JsonSerializerOptions
{
// ... default configuration
};
}
// Serialize to JSON string from entity
public static string ToJson(this object data, JsonSerializerOptions options = null)
{
if (data == null)
{
return string.Empty;
}
return JsonSerializer.Serialize(data, options ?? _opts); // throw exception when data has Value Type body
}
// Deserialize to entity from JSON string
public Static T ToJson<T>(this string json, JsonSerializerOptions options = null)
{
if (string.IsNullOrWhiteSpace(json))
{
return default;
}
return JsonSerializer.Deserialize<T>(json, options ?? _opts); // throw exception when data has Value Type body
}
}
When I serialize an entity to JSON string by System.Text.Json.JsonSerializer (.NET 5.0), it throw an exception.
Deserialize also has the same exception.
var res0 = new Res();
var res0Json = res0.ToJson(); // Success (Correct JSON string)
var res1 = new Res<string>("a"); // body is Reference Type
var res1Json = res1.ToJson(); // Success (Correct JSON string)
var res2 = new Res<int>(1); // body is Value Type
var res2Json = res2.ToJson(); // Fail (Throw an exception: Object reference not set to an instance of an object.)
It seems that: Value Type CANNOT Serialize/Deserialize, but Reference Type CAN
How do I resolve the exception?
Thanks
Reactions are currently unavailable