Ellipsis17 Ellipsis17 - 4 months ago 22
JSON Question

Unable to Serialize Object to JSON Using DataContractJsonSerializer

I have taken the following code from https://msdn.microsoft.com/en-us/library/bb410770(v=vs.110).aspx and put it in a Visual Studio project.

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;
}
}


I receive the following runtime error:

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.


The exception occurs at this line:

ser.WriteObject(stream1, p);


That seems odd. Rather than marking the Person class, it seems to want me to mark the DataContractJsonSerializer class itself. Another odd thing is that I downloaded the sample code from MSDN and ran their version, which is basically the same as mine, without any trouble. Theirs is a VS2010 project, and they have the Person class in the same file as the class containing the Main method, but that shouldn't be making a difference. Can anyone tell me what I'm doing wrong?

Answer

The issue is on line DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(DataContractJsonSerializer)); it should be DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));