简体   繁体   中英

How to serialize an C# object to specific JSON

I wanted to serialize C# object to JSON using Newtonsoft. I am able to serialize object with properties but didn't get expected JSON. I tried with layout property but didn't worked for me.

Expected JSON:

[{"EmployeeID":100,"EmployeeName":"Pradeep","Layout":{"fillColor":function(rowIndex){return'#5d5e5f';},"hLineColor":function(i,node){return'#446b8e';}}}]

Object Employee:

public class Employee
    {
        public int EmployeeID
        {
            get;
            set;
        }
        public string EmployeeName
        {
            get;
            set;
        }
    }

Console class:

class Program
    {
        static void Main(string[] args)
        {
            List<Employee> lstemployee = new List<Employee>
            {
                new Employee()
                {
                    EmployeeID = 100,
                    EmployeeName = "Pradeep",
                }
            };

            string output = JsonConvert.SerializeObject(lstemployee);
            Console.WriteLine(output);
            Console.ReadLine();
        }
    }

It works fine for EmployeeID and EmployeeName property. JSON I get:

[{"EmployeeID":100,"EmployeeName":"Pradeep"}]

Not able to get JSON for layout property. Thanks in Advance.

Decorate your payload in below format. [ { "EmployeeID": 100, "EmployeeName": "Pradeep", "Layout": { "fillColor": "function(rowIndex){return'#5d5e5f';}", "hLineColor": "function(i,node){return'#446b8e';}" } } ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM