【发布时间】:2020-03-03 13:26:26
【问题描述】:
我有一个像这样的JSON:
{
"content": {
"shopCart": {
"numberOfItem": "string",
"shipCostsAmount": "string"
},
"items": {
[
{
"itemQuantity": "1",
"itemAmount": "200",
"itemShelf": "string",
},
"item2": {
"itemQuantity": "1",
"itemAmount": "250",
"itemShelf": "string",
},
"item3": {
"itemQuantity": "1",
"itemAmount": "3000",
"itemShelf": "string",
}
],
}
}
}
我想检查itemShelf 是否不同于Liquor,例如在所有三个项目中。
我可以为这样的一个项目做到这一点:
public bool CheckItemShelf(Content content)
{
var itemShelf = content.Items.Item1.itemShelf;
bool result;
if ((itemShelf == "Liquor"))
result = false;
else
result = true;
return result;
}
我怎样才能为三个(或更多)项目做到这一点?
编辑:
这是 Content 类:
public class Content {
/// <summary>
/// Gets or Sets ShopCart
/// </summary>
[DataMember(Name="shopCart", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "shopCart")]
public ShopCart ShopCart { get; set; }
/// <summary>
/// Gets or Sets Items
/// </summary>
[DataMember(Name="items", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "items")]
public Items Items { get; set; }
}
编辑 2:
我将 Items 更改为数组,我如何检查所有 itemShelf 值都不是 Liquor 并且有真假响应?
【问题讨论】:
-
发送一个字符串和你想检查的项目给函数而不是内容本身
-
尝试使用库来处理 JSON 数据。类似Newtonsoft.Json 或System.Text.Json
-
谢谢,我已经在使用 Newtonsoft.Json
-
为什么
items不是 JSON 数组?会让迭代更容易。 -
@phuzi、
[JsonProperty("items")] public Dictionary<string, Item> Items { get; set; }和瞧。无需更改原始Json。
标签: c# json asp.net-web-api