DataContract

服务契约定义了远程访问对象和可供调用的方法,数据契约则是服务端和客户端之间要传送的自定义数据类型。

一旦声明一个类型为DataContract,那么该类型就可以被序列化在服务端和客户端之间传送,如下所示。

      [DataContract]

     public class UserInfo

     {

          //….

    }
只有声明为DataContract的类型的对象可以被传送,且只有成员属性会被传递,成员方法不会被传递。WCF对声明为DataContract的类型提供更加细节的控制,可以把一个成员排除在序列化范围以外,也就是说,客户端程序不会获得被排除在外的成员的任何信息,包括定义和数据。默认情况下,所有的成员属性都被排除在外,因此需要把每一个要传送的成员声明为DataMember,如下所示。

    [DataContract]

    public class UserInfo

    {

        [DataMember]

        public string UserName

        {

            get;

            set;

        }

        [DataMember]

        public int Age

        {

            get;

            set;

        }

        [DataMember]

        public string Location

        {

            get;

            set;

        }
[IgnoreDataMember]
public string Zodiac { get; set; } }

上面这段代码把UserInfo类声明为DataContract,将UserName、Age、Location这3个属性声明为DataMember(数据成员)。Zodiac成员没有被声明为DataMember,因此在交换数据时,不会传输Zodiac的任何信息。

声明为DataMember的成员也可以自定义客户端可见的名称,例如:

[DataMember(Name="Name")]

public string UserName

{

     get;

     set;

}
using System.Web.Script.Serialization in the .NET framework
public class User {
public int Id { get; set; }
public string Name { get; set; }
[ScriptIgnore]
public bool IsComplete
{
get { return Id > && !string.IsNullOrEmpty(Name); }
}
} //{ Id: 3, Name: 'Test User' }

If you are using Json.Net attribute [JsonIgnore] will simply ignore

public class Car
{
// included in JSON
public string Model { get; set; }
public DateTime Year { get; set; }
public List<string> Features { get; set; } // ignored
[JsonIgnore]
public DateTime LastModified { get; set; }
}

jsonignore demo:

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
[JsonObject(MemberSerialization.OptIn)]
public class User
{
[JsonProperty(PropertyName = "ID")]
public int Unid { get; set; } [JsonProperty]
public string UserName { get; set; } [JsonProperty]
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime CreateTime { get; set; } [JsonIgnoreAttribute]
public string PasssWord { get; set; } public string Memo { get; set; } [JsonProperty("userName")]
public string UserName{ set; get; }
}
}

JsonObjectAttribute

这个标签的成员序列化标志指定成员序列化是opt-in(要序列化的成员必须带有JsonProperty或DataMember标签)还是opt-out(默认所有的都会序列化,但通过JsonIgnoreAttribute标签可以忽略序列化。opt-out是json.net默认的)。

JsonPropertyAttribute

允许被序列化的成员自定义名字。这个标签同时标示出:在成员序列化设置为opt-in的时候,成员会被序列化。

JsonIgnoreAttribute

忽略域或属性的序列化

JsonConverterAttribute

用于指派转换对象的JsonSerializer。

这个标签可以修饰类或类成员。用于修饰类时,通过此标签指派的JsonConverter会被设置为序列化类的默认方式。用于修饰属性或域成员时,被指派的JsonConverter会序列化它们的值。

Or you can use DataContract and DataMember attribute to selectively serialize/deserialize properties/fields.

[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; }
}

将一个类序列化成JSON或XML时,如果某个字段或属性不想被序列化,则可以使用以下Attribute:

1、[Newtonsoft.Json.JsonIgnore]特性:使用Newtonsoft.Json序列化时字段不会被序列化。

2、[System.Web.Script.Serialization.ScriptIgnore]特性:使用JavaScriptSerializer序列化时字段不会被序列化。

3、[System.Xml.Serialization.XmlIgnore]特性:字段不会被序列化成XML。

实例:将用户信息类序列化成JSON和XML格式,其中电子邮件字段不被序列化。

1、创建用户信息类

/// <summary>
/// 用户信息类
/// </summary>
public class UserInfo
{
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; } /// <summary>
/// 年龄
/// </summary>
public int Age { get; set; } /// <summary>
/// 电子邮件
/// </summary>
[Newtonsoft.Json.JsonIgnore]
[System.Web.Script.Serialization.ScriptIgnore]
[System.Xml.Serialization.XmlIgnore]
public string Email { get; set; }
}

2、实现功能

static void Main(string[] args)
{
//创建用户信息
UserInfo user = new UserInfo();
user.Name = "张三";
user.Age = ;
user.Email = "zhangsan@qq.com"; //1、使用Newtonsoft转JSON
string newtonStr = JsonConvert.SerializeObject(user); //2、使用JavaScriptSerializer类转JSON
JavaScriptSerializer serializer = new JavaScriptSerializer();
string serializedStr = serializer.Serialize(user); //3、XML序列化
string xmlStr = XmlSerialize<UserInfo>(user); System.Console.ReadLine();
} //XML序列化方法
public static string XmlSerialize<T>(T obj)
{
using (StringWriter sw = new StringWriter())
{
Type t = obj.GetType();
XmlSerializer serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(sw, obj);
sw.Close();
return sw.ToString();
}
}

执行结果

1、使用Newtonsoft转JSON输出结果:{"Name":"张三","Age":25}

2、使用JavaScriptSerializer类转JSON输出结果:{"Name":"张三","Age":25}

3、XML序列化结果:
<?xml version="1.0" encoding="utf-16"?>
<UserInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>张三</Name>
  <Age>25</Age>
</UserInfo>

参考:

https://stackoverflow.com/questions/10169648/how-to-exclude-property-from-json-serialization/10169675#10169675

https://blog.csdn.net/pan_junbiao/article/details/82827978 C#中类的字段或属性不被序列化成JSON或XML

https://www.cnblogs.com/baobaodong/p/4647694.html    Json.net 忽略实体某些属性的序列化

最新文章

  1. 变通实现微服务的per request以提高IO效率(三)
  2. vs2010下C++调用lib或dll文件
  3. Intellij Idea中运行tomcat 报內存溢出 解决方案 火龙战士 火龙战士
  4. web安全测试
  5. 由chrome剪贴板问题研究到了js模拟鼠标键盘事件
  6. 图形显示之RGB
  7. Climbing Stairs - Print Path
  8. CSS常用的属性命名
  9. codevs 1171 潜伏者
  10. LeetCode_Interleaving String
  11. SQL 递归 可以用于权限查找。迭代自身没有用递归函数。
  12. 屏幕适配/autoLayout autoresizingMask
  13. Android:ImageView控件显示图片
  14. [51nod 1515] 明辨是非
  15. CF739E Gosha is hunting DP+wqs二分
  16. Codeforces Round #446 Div. 1
  17. wampserver安装之后出现“无法启动,因为计算机中丢失了msvr110.dll”
  18. GDAL对TIF创建内建金字塔一个问题
  19. 3D打印软件工具
  20. bzoj千题计划178:bzoj2425: [HAOI2010]计数

热门文章

  1. 如何11 周打造全能Python工程师!
  2. Linux命令——yum
  3. Linux命令——getent
  4. Kubernetes日志采集
  5. DataTable 删除数据后重新加载
  6. JDK源码那些事儿之LinkedBlockingQueue
  7. Robot Framework--pybot命令
  8. GeoJSON与GeoBuf互相转换
  9. LeetCode刷题分类-解题模式
  10. MongoDB Wiredtiger存储引擎实现原理