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

本文关键字:对象 序列化 JSON DataContractJsonSerializer | 更新日期: 2023-09-27 18:01:00

我从https://msdn.microsoft.com/en-us/library/bb410770(v=vs.110(.aspx并将其放入Visual Studio项目中。

程序.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方法的类在同一个文件中,但这应该没有什么区别。有人能告诉我我做错了什么吗?

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

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