var eans = myDeserializedClass.listings
.Select(x => new { x.amount, x.variant.variantName ?? " "})
.Where(x => x.variantName != null)
.ToArray();
上面的代码不起作用。在这种情况下,我如何替换空值?
x.variant.variantName ?? " "
当我创建??““时出现错误。x1c 0d1x
非常类似的代码与字段的名称(如图所示)编译得很好:
var eans = myDeserializedClass.listings
.Select(x => new { x.amount, V = x.variant.variantName ?? " "})
.Where(x => x.V != null)
.ToArray();
我尝试了很多东西,但无法找到解决方案来替换此选择中的空值
类看起来像:
public class Ask888
{
public string askId { get; set; }
public DateTime askCreatedAt { get; set; }
public DateTime askUpdatedAt { get; set; }
public DateTime askExpiresAt { get; set; }
}
public class Listing888
{
public string listingId { get; set; }
public string status { get; set; }
public string amount { get; set; }
public string currencyCode { get; set; }
public string inventoryType { get; set; }
public DateTime createdAt { get; set; }
public DateTime updatedAt { get; set; }
public Product888 product { get; set; }
public Variant888 variant { get; set; }
public object batch { get; set; }
public Ask888 ask { get; set; }
public object order { get; set; }
}
public class Product888
{
public string productId { get; set; }
public string productName { get; set; }
}
public class Root888
{
public int count { get; set; }
public int pageNumber { get; set; }
public int pageSize { get; set; }
public bool hasNextPage { get; set; }
public List<Listing888> listings { get; set; }
}
public class Variant888
{
public string variantId { get; set; }
public string variantName { get; set; }
public string variantValue { get; set; }
}
最后我就这样一直犯错误;/
string json = response.Content.ToString();
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore
};
Root888 myDeserializedClass = JsonConvert.DeserializeObject<Root888>(json, settings);
var eans = myDeserializedClass.listings
.Select(x => new { x.listingId, x.product.productId, x.status, x.amount, variantName = x.variant.variantName ?? " ", variantId = x.variant.variantId ?? " ", variantValue = x.variant.variantValue ?? " " })
.ToArray();
错误仍然
2条答案
按热度按时间aoyhnmkz1#
问题是variant为null,因此无法获取null对象的变量名
你有代码:
这只处理variantName为null的情况。但是包含variantName的父对象呢?如果它为null呢?
将其改为在variantName之前使用?.。然后,如果变量为null,则null传播运算符??实际上有一些可用的东西可以使用。
这应该行得通:
wvt8vs2t2#
您需要命名匿名类型的成员:
关键点:
variantName = x.variant.variantName??““