【问题标题】:Output id instead of the full object when serializing a list of objects序列化对象列表时输出 id 而不是完整对象
【发布时间】:2012-08-05 01:15:44
【问题描述】:

我与MVC 4的Web API,撞上了序列化问题的工作我无法找到答案。上代码...

假设我有以下课程:

public class Item {
    public int ID;
    public String Name;
    public bool Active;
}

public class Source {
    public int ID;
    public int Name;
}

Item 的序列化列表如下所示:

{
    ID: 1,
    Name: "That big thing",
    Active: true,
    Source: {
        ID: 1,
        Name: "The street"
    }
}

如果有很多在我的列表中的项目化每个源到对象的将获得低效。我想要做的只是在列表中获取源 ID。比如:

{
    ID: 1,
    Name: "That big thing",
    Active: true,
    Source: 1
}

【问题讨论】:

    标签: .net asp.net-mvc-4 json.net asp.net-web-api


    【解决方案1】:

    根据您的序列化项目列表,我假设 Item 类还包含 Source 属性,例如:

    public class Item {
        public int ID;
        public String Name;
        public bool Active;
        public Source Source;
    }
    

    如果是这种情况,您可以将 XmlIgnore 属性添加到 Source 属性,然后将源的 id 公开为新的 SourceID 属性:

        public class Item
        {
            public int ID;
            public String Name;
            public bool Active;
            [XmlIgnore]
            public Source Source;
            [XmlElement("Source")]
            public int SourceID
            {
                get
                {
                    if (Source != null)
                    {
                        return Source.ID;
                    }
                    else
                    {
                        return 0;
                    }
                }
                set
                {
                    // ignore incoming values
                }
            }
        }
    

    json 库可能不支持 Xml 属性;如果是这样的话,你可以使用它对应的属性(即JsonIgnore、JsonProperty)。

    【讨论】:

      【解决方案2】:

      此处发布的 [JsonIgnore] 建议不错,但它仅适用于 JSON.NET 序列化。

      要以通用方式执行此操作,请添加对 System.Runtime.Serialization DLL 的引用并相应地装饰您的模型:

      [DataContract]
      public class Source
      {
          [DataMember]
          public int ID;
      
          public int Name;
      }
      

      这将省略您在 Web API 中使用的任何 MediaTypeFormatting 中的 Name 属性,即

      <Active>true</Active>
      <ID>1</ID>
      <Name>test</Name>
      <Source>
       <ID>1</ID>
      </Source>
      

      "ID":1,
      "Name":"test",
      "Active":true,
      "Source":{"ID":1}
      

      【讨论】:

        猜你喜欢
        • 2020-07-19
        • 2013-01-18
        • 2019-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-10
        相关资源
        最近更新 更多