【问题标题】:Serialize only the collection of the class仅序列化类的集合
【发布时间】:2020-08-03 19:29:05
【问题描述】:

我有以下课程。

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

我只需要序列化列表审批者,而不需要序列化其他属性。 目前我正在使用以下代码

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

它返回所有属性,但我只需要列表项。谁能告诉我该怎么做?

非常感谢您的帮助:)

【问题讨论】:

  • 请不要发送带有标签的垃圾邮件。另外,不推荐使用JavaScriptSerializer

标签: c# json javascriptserializer


【解决方案1】:

你有两个选择:

使用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; }
}

或者我认为以下也应该有效:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    • 2018-11-20
    • 1970-01-01
    相关资源
    最近更新 更多