Reputation: 48
I'm trying to create this JSON string in C#
[
{
accountId = 123,
reportType = 1,
reportTypeDesc = "Daily"
},
{
accountId = 123,
reportType = 1,
reportTypeDesc = "Daily"
},
{
accountId = 123,
reportType = 1,
reportTypeDesc = "Daily"
}
]
I tried this way to do this json , here is my code :
var body = new []
new
{
accountId = 123,
reportType = 1,
reportTypeDesc = "Daily"
},
new
{
accountId = 123,
reportType = 1,
reportTypeDesc = "Daily"
},
new
{
accountId = 123,
reportType = 1,
reportTypeDesc = "Daily"
},
But I have compiler errors in "new[]" area
What is the right way to make this Json ? i tried all lots of different variation but nothing works
Upvotes: 0
Views: 404
Reputation: 4222
Try to use newtonsoft Json.NET for this, see how:
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);
See it working in my .NET Fiddle.
Upvotes: 1
Reputation: 60
The best way to work around with Json
in c#
or VB.Net
is to have a great library like, Newtonsoft.Json
. This will make your whole work lots easier and quicker. So, just download that library and try coding.
Remedy
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);
}
Execution
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);
}
Upvotes: 0