Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Convert C# Class Properties Into Json File

Tags:

json

c#

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
  }
]
}
like image 803
Rauf Abid Avatar asked Dec 01 '22 12:12

Rauf Abid


2 Answers

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

like image 171
Jon Skeet Avatar answered Dec 05 '22 01:12

Jon Skeet


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);
}
like image 40
Mark Shevchenko Avatar answered Dec 05 '22 00:12

Mark Shevchenko