2016-02-22 116 views
1

怎麼會從我的json最後一個逗號:我得到這個作爲輸出JSON從c#中刪除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(); 

請幫幫忙! 謝謝

+5

是否有一個很好的理由你使用stringbuilder來手動創建json字符串?有像JSON.Net這樣的庫可以爲你做到這一點,還有額外的好處,他們將創建有效的JSON並且已經得到廣泛的測試。 –

+0

你的意思是這樣的:json_result.LastIndexOf(「,」)== strgroupids.Length-1? json_result.Remove(strgroupids.Length - 1):json_result; – codebased

+0

只需修剪手動構建的字符串中的最後一個字符?爲什麼你首先手動構建JSON? – David

回答

5

我覺得這種方法是最好的選擇。

json_result.TrimEnd(',') 
+4

我會認爲使用JSON序列化器將是更好的選擇。 – David

+0

是的)你是對的) – NikitaKo

1

只要在return語句前面一行,您可以將構建器的子字符串的長度爲-1。像下面

 if(json_result.Length > 0) 
     { 
      json_result.Remove(json_result.Length - 1, 1); 
     } 
+1

非常感謝...它適用於我.... :) –

0

即使創建一個JSON這種方式是不是最好的一個,一個建議,當你的東西串聯串片段,我可以給是使用string.Join()方法。這將逗號放在必需的位置並使代碼可讀。

+1

你能分享一些示例代碼嗎? –