You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// 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
The text was updated successfully, but these errors were encountered:
It should be an internal bug. NullReferenceException should never be thrown in library code. Arguments verification failure should throw other exceptions.
It should be an internal bug. NullReferenceException should never be thrown in library code. Arguments verification failure should throw other exceptions.
The code CAN RUN without exception in .NET Core 3.1 or before.
Here is class and extend function
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.
It seems that: Value Type CANNOT Serialize/Deserialize, but Reference Type CAN
How do I resolve the exception?
Thanks
The text was updated successfully, but these errors were encountered: