我正在项目中使用System.Text.Json
,因为我需要处理大文件,所以决定使用它来处理GraphQL响应。
由于GraphQL的特殊性,有时我会得到高度嵌套的响应,这些响应不是固定的,也不适合映射到类。我通常需要检查响应中的一些属性。
我的问题在于JsonElement
。检查嵌套属性感觉非常笨拙,我觉得应该有更好的方法来解决这个问题。
例如,考虑下面模拟我收到的响应的代码。我只想检查2个属性(id和originalSrc)是否存在,如果存在则获取它们的值,但感觉代码很麻烦。是否有更好/更清晰/更简洁的编写方式呢?
var raw = @"{
""data"": {
""products"": {
""edges"": [
{
""node"": {
""id"": ""gid://shopify/Product/4534543543316"",
""featuredImage"": {
""originalSrc"": ""https://cdn.shopify.com/s/files/1/0286/pic.jpg"",
""id"": ""gid://shopify/ProductImage/146345345339732""
}
}
}
]
}
}
}";
var doc = JsonSerializer.Deserialize<JsonElement>(raw);
JsonElement node = new JsonElement();
string productIdString = null;
if (doc.TryGetProperty("data", out var data))
if (data.TryGetProperty("products", out var products))
if (products.TryGetProperty("edges", out var edges))
if (edges.EnumerateArray().FirstOrDefault().ValueKind != JsonValueKind.Undefined && edges.EnumerateArray().First().TryGetProperty("node", out node))
if (node.TryGetProperty("id", out var productId))
productIdString = productId.GetString();
string originalSrcString = null;
if(node.ValueKind != JsonValueKind.Undefined && node.TryGetProperty("featuredImage", out var featuredImage))
if (featuredImage.TryGetProperty("originalSrc", out var originalSrc))
originalSrcString = originalSrc.GetString();
if (!string.IsNullOrEmpty(productIdString))
{
//do stuff
}
if (!string.IsNullOrEmpty(originalSrcString))
{
//do stuff
}
代码量不算很多,但检查几个属性是非常常见的,我希望有一种更清晰、更易读的方法。