在 C# 中从 json 中删除最后一个逗号
本文关键字:最后一个 删除 中从 json | 更新日期: 2023-09-27 18:35:36
我怎么能从我的 json 中最后一个逗号:我把它作为输出 json
{Floor_Id:"1094",Booth_Count:12},{Floor_Id:"1095",Booth_Count:10},
这是我的 C# 代码:
StringBuilder json_result = new StringBuilder();
List<XElement> industries = ExpoHallXML.Descendants("industry").ToList();
if (industries != null && industries.Count > 0)
{
foreach (XElement industry in industries)
{
foreach (XElement floor in industry.Descendants("floor"))
{
if (floor.Attribute("id").Value != "0")
{
json_result.Append("{");
json_result.Append("Floor_Id:" + cmh.json_str(floor.Attribute("id").Value) + ",");
int booth_count = 0;
foreach (XElement page in floor.Descendants("page"))
{
booth_count = page.Descendants("booth").Count();
json_result.Append("Booth_Count:" + booth_count +"},");
}
}
}
}
}
return json_result.ToString();
请帮忙!谢谢
我认为这种方法是最好的选择。
json_result.TrimEnd(',')
只需在
return 语句之前一行,您就可以获取长度为 -1 的构建器的子字符串。像下面一样
if(json_result.Length > 0)
{
json_result.Remove(json_result.Length - 1, 1);
}
即使以这种方式创建 JSON 不是首选,当您通过某些东西连接字符串片段时,我可以给出的建议是使用该字符串。Join() 方法。这会将逗号放在所需的位置,并使代码可读。