繁体   English   中英

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

[英]Unable to Serialize Object to JSON Using DataContractJsonSerializer

我从https://msdn.microsoft.com/zh-cn/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();
        }
    }
}

人.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 ser = new DataContractJsonSerializer(typeof(DataContractJsonSerializer)); 应该是DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM