我试图在C#中创建这个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的正确方法是什么?我尝试了很多不同的变化,但没有任何作用
答案 0 :(得分: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中查看它。
答案 1 :(得分:0)
在Json
或c#
中使用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);
}