如何使用 DataContractJsonSerializerHow to use DataContractJsonSerializer

备注

本文介绍 DataContractJsonSerializerThis article is about DataContractJsonSerializer. 对于涉及序列化和反序列化 JSON 的大多数方案,我们建议在system.web 命名空间中提供 api。For most scenarios that involve serializing and deserializing JSON, we recommend the APIs in the System.Text.Json namespace.

JSON(JavaScript 对象符号)是一种高效的数据编码格式,可用于在客户端浏览器和支持 AJAX 的 Web 服务之间快速交换少量数据。JSON (JavaScript Object Notation) is an efficient data encoding format that enables fast exchanges of small amounts of data between client browsers and AJAX-enabled Web services.

本文演示如何将 .NET 类型对象序列化为 JSON 编码数据,然后将 JSON 格式的数据反序列化为 .NET 类型的实例。This article demonstrates how to serialize .NET type objects into JSON-encoded data and then deserialize data in the JSON format back into instances of .NET types. 此示例使用数据协定演示用户定义的 Person 类型的序列化和反序列化,并使用 DataContractJsonSerializerThis example uses a data contract to demonstrate serialization and deserialization of a user-defined Person type and uses DataContractJsonSerializer.

通常,当你在服务操作中使用在支持 AJAX 的终结点上公开的数据协定类型时,将 Windows Communication Foundation 自动处理 JSON 序列化和反序列化。Normally, JSON serialization and deserialization are handled automatically by Windows Communication Foundation (WCF) when you use data contract types in service operations that are exposed over AJAX-enabled endpoints. 但是,在某些情况下,您可能需要直接处理 JSON 数据。However, in some cases you may need to work with JSON data directly.

本文基于DataContractJsonSerializer 示例This article is based on the DataContractJsonSerializer sample.

为 Person 类型定义数据协定To define the data contract for a Person type

  1. 通过将 Person 附加到类并将 DataContractAttribute 特性附加到要序列化的成员,为 DataMemberAttribute 定义数据协定。Define the data contract for Person by attaching the DataContractAttribute to the class and DataMemberAttribute attribute to the members you want to serialize. 有关数据协定的详细信息,请参阅设计服务协定For more information about data contracts, see Designing service contracts.

    [DataContract]
    internal class Person
    {
        [DataMember]
        internal string name;
    
        [DataMember]
        internal int age;
    }
    

将 Person 类型的实例序列化为 JSONTo serialize an instance of type Person to JSON

备注

如果在服务器上的传出答复序列化过程中出现错误,或出于其他原因导致错误,则可能不会将其作为错误返回到客户端。If an error occurs during serialization of an outgoing reply on the server or for some other reason, it may not get returned to the client as a fault.

  1. 创建 Person 类型的实例。Create an instance of the Person type.

    var p = new Person();
    p.name = "John";
    p.age = 42;
    
  2. 使用 DataContractJsonSerializerPerson 对象序列化到内存流。Serialize the Person object to a memory stream by using the DataContractJsonSerializer.

    var stream1 = new MemoryStream();
    var ser = new DataContractJsonSerializer(typeof(Person));
    
  3. 使用 WriteObject 方法将 JSON 数据写入到流中。Use the WriteObject method to write JSON data to the stream.

    ser.WriteObject(stream1, p);
    
  4. 显示 JSON 输出。Show the JSON output.

    stream1.Position = 0;
    var sr = new StreamReader(stream1);
    Console.Write("JSON form of Person object: ");
    Console.WriteLine(sr.ReadToEnd());
    

从 JSON 反序列化 Person 类型的实例To deserialize an instance of type Person from JSON

  1. 通过使用 PersonReadObject 方法,将 JSON 编码数据反序列化为一个新的 DataContractJsonSerializer 实例。Deserialize the JSON-encoded data into a new instance of Person by using the ReadObject method of the DataContractJsonSerializer.

    stream1.Position = 0;
    var p2 = (Person)ser.ReadObject(stream1);
    
  2. 显示结果。Show the results.

    Console.WriteLine($"Deserialized back, got name={p2.name}, age={p2.age}");
    

示例Example

// Create a User object and serialize it to a JSON stream.
public static string WriteFromObject()
{
    // Create User object.
    var user = new User("Bob", 42);

    // Create a stream to serialize the object to.
    var ms = new MemoryStream();

    // Serializer the User object to the stream.
    var ser = new DataContractJsonSerializer(typeof(User));
    ser.WriteObject(ms, user);
    byte[] json = ms.ToArray();
    ms.Close();
    return Encoding.UTF8.GetString(json, 0, json.Length);
}

// Deserialize a JSON stream to a User object.
public static User ReadToObject(string json)
{
    var deserializedUser = new User();
    var ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
    var ser = new DataContractJsonSerializer(deserializedUser.GetType());
    deserializedUser = ser.ReadObject(ms) as User;
    ms.Close();
    return deserializedUser;
}

备注

对于包含多个具有相同名称的成员的数据协定,JSON 序列化程序将引发一个序列化异常,如以下示例代码中所示。The JSON serializer throws a serialization exception for data contracts that have multiple members with the same name, as shown in the following sample code.

[DataContract]
public class TestDuplicateDataBase
{
    [DataMember]
    public int field1 = 123;
}

[DataContract]
public class TestDuplicateDataDerived : TestDuplicateDataBase
{
    [DataMember]
    public new int field1 = 999;
}

另请参阅See also