【发布时间】:2020-08-16 14:53:34
【问题描述】:
我在我的项目中使用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
}
这不是大量的代码,但检查少数属性是如此普遍,我想要一种更简洁、更易读的方法。
【问题讨论】:
标签: c# .net-core system.text.json