Rauf Abid Rauf Abid - 1 year ago 133
C# Question

How To Convert C# Class Properties Into Json File

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.

"Id": 10,
"FirstName ":"John",
"Address":My add1

Answer Source

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
    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...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download