无法使用DataContractJsonSerializer将对象序列化为JSON

时间:2016-08-05 19:48:01

标签: c# json serialization datacontractjsonserializer

我从https://msdn.microsoft.com/en-us/library/bb410770(v=vs.110).aspx获取了以下代码并将其放在Visual Studio项目中。

Program.cs的

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

namespace DataContractJsonSerializer_Example
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a person object.
            Person p = new Person();
            p.name = "John";
            p.age = 42;

            // Serialize the Person object to a memory stream using DataContractJsonSerializer.
            MemoryStream stream1 = new MemoryStream();
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(DataContractJsonSerializer));

            // Use the WriteObject method to write JSON data to the stream.
            ser.WriteObject(stream1, p);

            // Show the JSON output.
            stream1.Position = 0;
            StreamReader sr = new StreamReader(stream1);
            Console.Write("JSON form of Person object: ");
            Console.WriteLine(sr.ReadToEnd());
            Console.Read();
        }
    }
}

Person.cs

using System.Runtime.Serialization;

namespace DataContractJsonSerializer_Example
{
    [DataContract]
    class Person
    {
        [DataMember]
        internal string name;

        [DataMember]
        internal int age;
    }
}

我收到以下运行时错误:

An unhandled exception of type 'System.Runtime.Serialization.InvalidDataContractException' occurred in System.Runtime.Serialization.dll

Additional information: Type 'System.Runtime.Serialization.Json.DataContractJsonSerializer' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute.  If the type is a collection, consider marking it with the CollectionDataContractAttribute.

此行发生异常:

ser.WriteObject(stream1, p);

这看起来很奇怪。它似乎要求我自己标记DataContractJsonSerializer类,而不是标记Person类。另一个奇怪的事情是我从MSDN下载了示例代码并运行了他们的版本,这与我的版本基本相同,没有任何问题。他们是一个VS2010项目,他们将Person类与包含Main方法的类放在同一个文件中,但这不应该有所作为。谁能告诉我我做错了什么?

1 个答案:

答案 0 :(得分:1)

问题在线 DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(DataContractJsonSerializer)); 它应该是 DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));