[英]How datetime null serialization in json .net 5 blazor
In blazor client side + api在 blazor 客户端 + api
Just to be clear: I want it as generic as possible so this one method in controller executes a stored procedure that can query many tables and return different result sets without knowing of type that this will be parsed into later in frontend wasm.明确一点:我希望它尽可能通用,因此 controller 中的这个方法执行一个存储过程,该过程可以查询许多表并返回不同的结果集,而无需知道稍后将在前端 wasm 中解析的类型。 So I cannot return
List<MYclass>
because it will be different every time.所以我不能返回
List<MYclass>
因为它每次都会不同。
In api controller I have like this to serialize table that have 3 columns在 api controller 我喜欢这样序列化具有 3 列的表
ID, IDSiec, data
The data
is datetime type, and I serialize this dataTable like this data
是日期时间类型,我像这样序列化这个dataTable
da.Fill(dt);
connection.Close();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
foreach (DataRow dr in dt.Rows)
{
var row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return Ok(rows);
and then in wasm然后在wasm
class MYclass
{
public int ID { get; set; }
public int IDSiec { get; set; }
public DateTime? data { get; set; }
}
.....
await response.Content.ReadFromJsonAsync<List<MYclass>>());
And if in database all records have this data
filed then it is ok but if this data
is null then in json for this record I get如果在数据库中所有记录都有这个
data
,那么没关系,但是如果这个data
是 null 然后在 json 中我得到这个记录
"Data":{},
and it fails with an error它失败并出现错误
The JSON value could not be converted to System.Nullable [System.DateTime].
JSON 值无法转换为 System.Nullable [System.DateTime]。 Path: $[0].Data |
路径:$[0].Data | LineNumber: 0
行号:0
How should I handle this kind of situation?我应该如何处理这种情况? Force somehow this serializer to send NULL.
以某种方式强制此序列化程序发送 NULL。 Object is not nulable so thats why it sends {} instead of null value probably
Object 不是 nulable 所以这就是为什么它发送 {} 而不是 null 值可能
Sample json out样品 json 出
[{"ID":1141818,"IDSiec":94,"Data":{},...}]
Thanks and regards谢谢并恭祝安康
foreach (DataColumn col in dt.Columns)
{
if (dr[col] != null) // or test against DbNull or something
{
row.Add(col.ColumnName, dr[col]);
}
}
the final answer from the comment below:以下评论的最终答案:
if (dr[col] == DBNull.Value)
row.Add(col.ColumnName, null);
else
row.Add(col.ColumnName, dr[col]);
I do agree with the safety concerns raised here.我同意这里提出的安全问题。 But this answer is about how to handle NULL values from a Db API.
但这个答案是关于如何处理来自 Db API 的 NULL 值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.