【问题标题】:Serialize object into JSON but only include properties with the [DataMember] attribute将对象序列化为 JSON,但仅包含具有 [DataMember] 属性的属性
【发布时间】:2014-11-23 18:43:24
【问题描述】:

如何将给定对象序列化为 JSON,但只包含具有 [DataMember] 属性的属性。

User MyUser = new User();
string MessageJson = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(MyUser);

public class User
{
    [DataMember]
    public string username { get; set; }

    public string password { get; set; }
}

【问题讨论】:

    标签: c# json


    【解决方案1】:

    您需要为此使用DataContractJsonSerializer。 请注意,我认为您还需要类上的 DataContract 属性。

    【讨论】:

    • 我会回答上面的评论 - 是的,你可以。
    【解决方案2】:

    您可以使用JSON.Net

    如果一个类有很多属性,而您只想序列化其中的一小部分,那么将 JsonIgnore 添加到所有其他属性将是乏味且容易出错的。解决这种情况的方法是将 DataContractAttribute 添加到类中,将 DataMemberAttributes 添加到要序列化的属性中。这是选择加入序列化,与使用 JsonIgnoreAttribute 的选择退出序列化相比,仅对您标记的属性进行序列化。

    [DataContract]
    public class Computer
    {
      // included in JSON
      [DataMember]
      public string Name { get; set; }
      [DataMember]
      public decimal SalePrice { get; set; }
    
      // ignored
      public string Manufacture { get; set; }
      public int StockCount { get; set; }
      public decimal WholeSalePrice { get; set; }
      public DateTime NextShipmentDate { get; set; }
    }
    

    【讨论】:

    • 感谢您的回答 - 我希望使用 .Net 本机对象。但看起来这是要走的路。
    【解决方案3】:

    您可以将[ScriptIgnore] 属性放在您不想包含在结果中的属性上。

    【讨论】:

    • 这并不能真正回答 OP 提出的问题。
    猜你喜欢
    • 2015-07-29
    • 2015-09-20
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-03
    相关资源
    最近更新 更多