【发布时间】:2021-08-25 15:41:59
【问题描述】:
我正在开发一个 C# 项目。以下是我的 JSON。我想从中删除“类型”:“产品”的“项目”:[],因为它会导致用户界面出现问题。在创建 JSON 时,我尝试使用 How to Ignoring Fields and Properties Conditionally During Serialization Using JSON.Net? 中描述的以下 Item 类来排除该值。但它没有工作,不知道为什么。或者,有没有办法在创建 JSON 后将其删除?
[
{
"Type":"Category",
"Order":1,
"id":"24",
"text":"abc",
"items":[
{
"Type":"Product",
"Order":0,
"id":1900,
"text":"abc product",
"items":[
]
}
]
},
{
"Type":"Category",
"Order":1,
"id":"6",
"text":"efg",
"items":[
{
"Type":"Product",
"Order":0,
"id":2446,
"text":"efg Product",
"items":[
]
},
{
"Type":"Product",
"Order":0,
"id":2447,
"text":"efg1 Product",
"items":[
]
}
]
}
]
[Serializable]
public class Item
{
public String Type { get; set; }
public int Order { get; set; }
public int id { get; set; }
public string text { get; set; }
public IList<Item> items { get; set; }
public bool ShouldSerializeitems()
{
return this.Type != "Product";
}
public Item()
{
items = new List<Item>();
}
}
foreach (Products product in products)
{
Item product = new Item();
product.id = Convert.ToInt32(product.GetProductID());
product.text = product.GetName();
product.Order = product.GetProductSortOrder();
product.Type = "Product";
Category.items.Add(product);
}
【问题讨论】:
-
所以你不想想修改JSON字符串,你想跳过空数组
-
我想通过删除 "Type":"Product" 下的 "items":[ ] 来修改 JSON 字符串。
-
不应该是
return this.Type != "Product";吗? -
是的,让我更正一下。我之前也试过。
-
我试图仅排除 public IList
- items { get;放; } 对应于 ShouldSerializeitems