打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
JSONSerializer.writeWithFieldName
 如何:对 JSON 数据进行序列化和反序列化
This content was manually translated to a higher quality standard. If you wish to further improve the quality of the translation, click the Edit button associated with the sentence that you wish to modify.
How to: Serialize and Deserialize JSON Data

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 topic 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 using theDataContractJsonSerializer. This example uses a data contract to demonstrate serialization and deserialization of a user-definedPersontype.

Normally, JSON serialization and deserialization is 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 is the scenario that this topic demonstrates.

Note

If an error occurs during serialization of an outgoing reply on the server or the reply operation throws an exception for some other reason, it may not get returned to the client as a fault.

This topic is based on the JSON Serialization sample.

To define the data contract for a Person

  • Define the data contract forPersonby attaching the DataContractAttribute to the class andDataMemberAttribute attribute to the members you want to serialize. For more information about data contracts, seeDesigning Service Contracts.

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

To serialize an instance of type Person to JSON

  1. Create an instance of thePersontype.

    Person p = new Person();
    p.name = "John";
    p.age = 42;
  2. Serialize thePersonobject to a memory stream using theDataContractJsonSerializer.

    MemoryStream stream1 = new MemoryStream();
    DataContractJsonSerializer 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;
    StreamReader 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 ofPersonby using the ReadObject method of theDataContractJsonSerializer.

    stream1.Position = 0;
    Person p2 = (Person)ser.ReadObject(stream1);
  2. Show the results.

    Console.Write("Deserialized back, got name=");
    Console.Write(p2.name);
    Console.Write(", age=");
    Console.WriteLine(p2.age);
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.
如何:对 JSON 数据进行序列化和反序列化

JSON(JavaScript 对象符号)是一种高效的数据编码格式,可用于在客户端浏览器和支持 AJAX 的 Web 服务之间快速交换少量数据。

本主题演示如何使用 DataContractJsonSerializer 将 .NET 类型对象序列化为 JSON 编码数据,然后将 JSON 格式的数据反序列化回 .NET 类型的实例。本示例使用数据协定来演示用户定义的Person类型的序列化和反序列化。

通常,当在通过支持 AJAX 的终结点公开的服务操作中使用数据协定类型时,Windows Communication Foundation (WCF) 会自动处理 JSON 序列化和反序列化。但是,在某些情况下您可能需要直接处理 JSON 数据,这正是本主题演示的方案。

说明

如果在服务器上序列化传出答复期间出现错误,或者答复操作由于某个其他原因引发异常,则可能不会将其作为错误返回到客户端。

本主题基于 JSON 序列化示例。

定义 Person 的数据协定

  • 通过将 DataContractAttribute 附加到类并将DataMemberAttribute 特性附加到要序列化的成员,为Person定义数据协定。有关以下内容的详细信息数据协定的更多信息,请参见设计服务协定

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

将 Person 类型的实例序列化为 JSON

  1. 创建Person类型的实例。

    Person p = new Person();
    p.name = "John";
    p.age = 42;
  2. 使用 DataContractJsonSerializer 将Person对象序列化为内存流。

    MemoryStream stream1 = new MemoryStream();
    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));
  3. 使用 WriteObject 方法将 JSON 数据写入到流中。

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

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

从 JSON 反序列化 Person 类型的实例

  1. 通过使用 DataContractJsonSerializer 的 ReadObject 方法,将 JSON 编码数据反序列化为一个新的Person实例。

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

    Console.Write("Deserialized back, got name=");
    Console.Write(p2.name);
    Console.Write(", age=");
    Console.WriteLine(p2.age);
对于包含多个具有相同名称的成员的数据协定,JSON 序列化程序将引发一个序列化异常,如以下示例代码中所示。
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
C#中,Json的序列化和反序列化的几种方式总结
[.net 面向对象程序设计进阶] (13) 序列化(Serialization)(五) JSON序列化利器 Newtonsoft.Json 及 通用Json类
json序列化整理
对象序列化
C#序列化与反序列化详解
ASP.NET中JSON的序列化和反序列化
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服