【问题标题】:Unable to Serialize Object to JSON Using DataContractJsonSerializer无法使用 DataContractJsonSerializer 将对象序列化为 JSON
【发布时间】:2016-08-05 19:48:01
【问题描述】:

我从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);

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

【问题讨论】:

  • 不要使用DataContractJsonSerializer。它很旧,很慢,并且不能很好地处理很多极端情况。那里有一百万个好的图书馆。我最喜欢的两个是 Json.NET 和 Jil,这取决于我的需要。我建议您考虑升级。

标签: c# json serialization datacontractjsonserializer


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2013-12-31
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多