简体   繁体   中英

Serialize only the collection of the class

I have a following class.

class Timesheet
    {
        public int ID { get; set; }
        public List<Employee> Approvers { get; set; }
        public Employee Resource { get; set; }
        public string Status { get; set; }
    }

And I need to serialize only the List Approvers and not the other properties. Currently I'm using the following code

JavaScriptSerializer serializer = new JavaScriptSerializer();
            var json = serializer.Serialize(tsheet);

Which returns all the properties but I need only the list items. Can anyone please tell me how can I do this?

Really appreciate the help:)

You have two choices:

Using the ScriptIgnoreAttribute :

public class Timesheet
{
    [ScriptIgnore]
    public int ID { get; set; }

    public List<Employee> Approvers { get; set; }

    [ScriptIgnore]        
    public Employee Resource { get; set; }

    [ScriptIgnore]        
    public string Status { get; set; }
}

or I think the following should also work:

var json = serializer.Serialize(new { Approvers = tsheet.Approvers });

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