简体   繁体   English

如何将C#对象序列化为特定的JSON

[英]How to serialize an C# object to specific JSON

I wanted to serialize C# object to JSON using Newtonsoft. 我想使用Newtonsoft将C#对象序列化为JSON。 I am able to serialize object with properties but didn't get expected JSON. 我能够序列化带有属性的对象,但没有得到预期的JSON。 I tried with layout property but didn't worked for me. 我尝试使用layout属性,但没有为我工作。

Expected JSON: 预期的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. 它适用于EmployeeID和EmployeeName属性。 JSON I get: 我得到的JSON:

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

Not able to get JSON for layout property. 无法获取布局属性的JSON。 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';}" } } ] [{“ EmployeeID”:100,“ EmployeeName”:“ Pradeep”,“ Layout”:{“ fillColor”:“ function(rowIndex){return'#5d5e5f';}”,“ hLineColor”:“ function(i,node ){return'#446b8e';}“}}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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