gpt4 book ai didi

c# 解析 json 值,检查是否为 null

转载 作者:太空宇宙 更新时间:2023-11-03 18:05:45 25 4
gpt4 key购买 nike

所以我有这个调用服务的 Web API,该服务又返回一个 json 字符串。字符串看起来有点像这样:

{
"title": "Test",
"slug": "test",
"collection":{ },
"catalog_only":{ },
"configurator":null
}

我已经大大减少了它,以便更容易看到我的问题。

当我进行 API 调用时,我会使用 Factory 方法来分解看起来像这样的响应:

    /// <summary>
/// Used to create a product response from a JToken
/// </summary>
/// <param name="model">The JToken representing the product</param>
/// <returns>A ProductResponseViewModel</returns>
public ProductResponseViewModel Create(JToken model)
{

// Create our response
var response = new ProductResponseViewModel()
{
Title = model["title"].ToString(),
Slug = model["slug"].ToString()
};

// Get our configurator property
var configurator = model["configurator"];

// If the configurator is null
if (configurator == null)
throw new ArgumentNullException("Configurator");

// For each item in our configurator data
foreach (var item in (JObject)configurator["data"])
{

// Get our current option
var option = item.Value["option"].ToString().ToLower();

// Assign our configuration values
if (!response.IsConfigurable) response.IsConfigurable = (option == "configurable");
if (!response.IsDesignable) response.IsDesignable = (option == "designable");
if (!response.HasGraphics) response.HasGraphics = (option == "graphics");
if (!response.HasOptions) response.HasOptions = (option == "options");
if (!response.HasFonts) response.HasFonts = (option == "fonts");
}

// Return our Product response
return response;
}
}

现在,如您所见,我正在获取我的配置器属性,然后检查它是否为空。json 字符串将 configurator 显示为 null,但当我在检查中放置断点时,它实际上将其值显示为 {}。我的问题是如何让它显示值 (null) 而不是这个括号响应?

最佳答案

您正在请求与 configurator key 关联的 JToken。有这样一个标记 - 它是一个空标记。

您可以通过以下方式检查:

if (configurator.Type == JTokenType.Null)

所以如果你想抛出 if either 有一个明确的 null token 或者 configurator 还没有完全指定,您可以使用:

if (configurator == null || configurator.Type == JTokenType.Null)

关于c# 解析 json 值,检查是否为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30706393/

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