2010-02-11 3 views
2

Я получил из (отличный) класс PropertyBag, а затем хочу сериализовать Json, используя DataContractJsonSerializer. К сожалению, динамические свойства не отображаются в JSON, несмотря на то, что они созданы с помощью DataContractAttribute. Как я могу сериализовать эти динамические свойства?DataContractJsonSerializer не видит DataMemberAttribute

using System; 
using System.ComponentModel; 
using System.IO; 
using System.Runtime.Serialization; 
using System.Runtime.Serialization.Json; 

namespace JsonProperties 
{ 
    [DataContract] 
    class MyClass : PropertyBag 
    { 
     static MyClass() 
     { 
      Attribute att_lat = new DisplayNameAttribute("Latitude"); 
      Attribute att_data = new DataMemberAttribute(); 

      Attribute[] attribs_lat = { att_lat, att_data }; 

      MyClass.AddProperty("_Latitude", typeof(String), attribs_lat); 
     } 
     [DataMember] 
     public Decimal latitude 
     { 
      get { return (Decimal)this["_Latitude"]; } 
      set 
      { // Validation etc. 
       this["_Latitude"] = value; 
      } 
     } 
    } 

    class Program 
     { 
      static void Main(string[] args) 
      { 
       Attribute attr1 = new DisplayNameAttribute("Dynamic Note Property"); 
       Attribute attr2 = new DataContractAttribute(); 
       Attribute[] attrs = { attr1, attr2 }; 

       MyClass.AddProperty("Notes", typeof(String), attrs); 
       MyClass location = new MyClass(); 

       location.latitude = 0.1M; 
       location["Notes"] = "Some text"; 

       DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(MyClass)); 
       dcjs.WriteObject(Console.OpenStandardOutput(), location); 
       Console.ReadLine(); 
      } 
     } 
    } 

ответ

1

Свойство «Примечание» должен быть украшен DataMemberAttribute для того, чтобы получить подобран сериализатором JSON. Не DataContractAttirbute, как вы используете здесь.

Смежные вопросы