Επεξεργασία

Κοινή χρήση μέσω


How to use DataContractJsonSerializer

Note

This article is about DataContractJsonSerializer. For most scenarios that involve serializing and deserializing JSON, we recommend the APIs in the System.Text.Json namespace.

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.

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. This example uses a data contract to demonstrate serialization and deserialization of a user-defined Person type and uses DataContractJsonSerializer.

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. However, in some cases you may need to work with JSON data directly.

This article is based on the DataContractJsonSerializer sample.

To define the data contract for a Person type

  1. 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;
    }
    

To serialize an instance of type Person to JSON

Note

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. Create an instance of the Person type.

    var p = new Person();
    p.name = "John";
    p.age = 42;
    
  2. Serialize the Person object to a memory stream by using the DataContractJsonSerializer.

    var stream1 = new MemoryStream();
    var ser = new DataContractJsonSerializer(typeof(Person));
    
  3. Use the WriteObject method to write JSON data to the stream.

    ser.WriteObject(stream1, p);
    
  4. Show the JSON output.

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

To deserialize an instance of type Person from JSON

  1. 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;
}

Note

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