2016-08-05 18 views
0

https://msdn.microsoft.com/en-us/library/bb410770(v=vs.110).aspxから次のコードを取り出し、Visual Studioプロジェクトに配置しました。DataContractJsonSerializerを使用してJSONにオブジェクトをシリアル化できません

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. 

例外は、この行で発生します。

これは奇妙に思えます。 Personクラスをマーキングするのではなく、DataContractJsonSerializerクラスそのものをマークすることが望ましいと思われます。別の奇妙なことは、MSDNからサンプルコードをダウンロードしてバージョンを稼働させたことです。バージョンは基本的に私と同じですが、何の問題もありません。それらのクラスはVS2010プロジェクトで、Mainメソッドを含むクラスと同じファイルにPersonクラスがありますが、違いはありません。誰かが私が間違っていることを教えてもらえますか?

+2

'DataContractJsonSerializer'を使用しないでくださいする必要がありますライン DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(DataContractJsonSerializer)); です。それは古くて遅く、コーナーケースをよく扱わない。そこには百万の良いライブラリがあります。私の2つのお気に入りは、私のニーズに応じて、Json.NETとJilです。アップグレードを検討することをおすすめします。 –

答えて

1

問題は、それが DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));

関連する問題