2015-12-31 99 views
0

我試圖創建在C#這JSON字符串創建複雜的JSON字符串

[ 
    { 
    accountId = 123, 
    reportType = 1, 
    reportTypeDesc = "Daily" 
    }, 
    { 
    accountId = 123, 
    reportType = 1, 
    reportTypeDesc = "Daily" 
    }, 
    { 
    accountId = 123, 
    reportType = 1, 
    reportTypeDesc = "Daily" 
    } 
] 

我想這種方式來做到這一點JSON,這裏是我的代碼:

var body = new [] 

      new 
      { 
       accountId = 123, 
       reportType = 1, 
       reportTypeDesc = "Daily" 
      }, 
       new 
      { 
       accountId = 123, 
       reportType = 1, 
       reportTypeDesc = "Daily" 
      }, 
       new 
      { 
       accountId = 123, 
       reportType = 1, 
       reportTypeDesc = "Daily" 
      }, 

但我的編譯器「new []」區域中的錯誤

使這個Json成爲正確的方法是什麼?我嘗試了所有許多不同的變化,但沒有任何工程

+3

你忘了括號:'新的[] {...}' –

+1

我一直快樂使用這個框架我的JSON序列化需要:http://www.newtonsoft.com/json如果您使用Visual Studio,可以使用nuget將其添加到您的解決方案。 – Paul

+0

http://stackoverflow.com/questions/331976/how-do-i-serialize-a-c-sharp-anonymous-type-to-a-json-string可能也有幫助。 – Paul

回答

1

嘗試使用newtonsoft Json.NET這個,怎麼看:

var body = new object []{ 
    new 
    { 
    accountId = 123, 
    reportType = 1, 
    reportTypeDesc = "Daily" 
    }, 
new 
    { 
     accountId = 123, 
     reportType = 1, 
     reportTypeDesc = "Daily" 
    }, 
new 
    { 
    accountId = 123, 
    reportType = 1, 
    reportTypeDesc = "Daily" 
    }, 
}; 
var jsonBody = JsonConvert.SerializeObject(body); 

看到它在my .NET Fiddle工作。

0

Jsonc#VB.Net變通辦法的最佳途徑是有一個偉大的圖書館,如Newtonsoft.Json。這將使您的整個工作更輕鬆快捷。所以,只需下載該庫並嘗試編碼。

補救

public class MainClass 
{ 
    public class Items 
    { 
     public int accountId, reportType; 
     public string reportTypeDesc; 
     public Items() 
     { 

     } 
     public Items(int accountId, int reportType, string reportTypeDesc) 
     { 
      this.accountId = accountId; 
      this.reportType = reportType; 
      this.reportTypeDesc = reportTypeDesc; 
     } 
    } 
    public List<Items> allItems = new List<Items>(); 
    public string toJson() => 
     JsonConvert.SerializeObject(allItems); 
} 

執行

private void Form1_Load(object sender, EventArgs e) 
    { 
     MainClass m = new MainClass(); 
     m.allItems.Add(new MainClass.Items(123, 1, "Daily")); 
     m.allItems.Add(new MainClass.Items(123, 1, "Daily")); 
     m.allItems.Add(new MainClass.Items(123, 1, "Daily")); 
     string json = m.toJson(); 
     richTextBox1.AppendText(json); 
    }