gpt4 book ai didi

c# - 如何创建其 ValueKind 等于 JsonValueKind.Null 的 JsonElement

转载 作者:行者123 更新时间:2023-12-05 02:50:27 28 4
gpt4 key购买 nike

此问题特定于 System.Text.Json 命名空间,而不是 Newtonsoft。我正在尝试为我的代码中的某个片段编写单元测试,我遇到以下情况:

var objString = JsonSerializer.Serialize(obj);
using var doc = JsonDocument.Parse(objString);
var root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Null)
{// do something here}

我不知道如何生成 JsonElement,其 ValueKind 等于 JsonValueKind.Null。我尝试在 obj 变量中传递下面提到的对象,但结果是 JsonValueKind.Object

new MyClass()
{
InnerMember = new InnerClass() { Data = null }
}

最佳答案

您得到 JsonValueKind.Object 是因为您正在查看 root 元素。只有一种情况是根元素有一种Null,那就是整个json字符串是:

null

演示:

var doc = JsonDocument.Parse("null");
var root = doc.RootElement;
if (root.ValueKind == JsonValueKind.Null)
{
// this will run
}

如果你想让JsonSerializer.Serialize产生null,只要传入null即可:

object obj = null;
var objString = JsonSerializer.Serialize(obj);

关于c# - 如何创建其 ValueKind 等于 JsonValueKind.Null 的 JsonElement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63682730/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com