Iam trying to create jsonObject and json array by using the c# class and its properties containing values. Please see the complete code below.
public class Product
{
public Int32 Id { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
public String Address { get; set; }
}
protected void Button1_Click(object sender, EventArgs e)
{
Product pr = new Product();
pr.Id = 10;
pr.FirstName = "John";
pr.LastName = "ab";
pr.Address = "My Add1";
string json = JsonConvert.SerializeObject(pr,Formatting.Indented);
System.IO.File.WriteAllText(@"d:\abcjson.json", json);
}
The above code give the below Output
{
"Id": 10,
"FirstName": "John",
"LastName": "ab",
"Address": My Add1,
}
But i need the following output followed by jsonObject and jsonArray. Please any guide how can i get the below output by using the above json code under button click. Thanks in advance.
{
"Product":[
{
"Id": 10,
"FirstName ":"John",
"lastName":"ab",
"Address":My add1
}
]
}
The thing to do is take look at the JSON you want. It's an object, with a Product
property, which is an array of product objects.
So the simplest way to do that is create a class modelling that:
public class JsonRoot
{
[JsonProperty("Product")]
public List<Product> Products { get; set; }
}
Then you can just use:
var root = new JsonRoot { Products = new List<Product> { pr } };
string json = JsonConvert.SerializeObject(root, Formatting.Indented);
You could use an anonymous type instead, potentially:
var root = new { Product = new[] { pr } };
I personally don't tend to like mixing anonymous types with named types for serialization, but it should work okay...
protected void Button1_Click(object sender, EventArgs e)
{
var pr = new
{
Product = new[]
{
new Product
{
Id = 10,
FirstName = "John",
LastName = "ab",
Address = "My Add1"
}
}
};
string json = JsonConvert.SerializeObject(pr,Formatting.Indented);
System.IO.File.WriteAllText(@"d:\abcjson.json", json);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With