2014-10-21 169 views
0

首先..我對JSON.NET或任何其他解析器不感興趣。只有DataContractJsonSerializerJSON使用.NET DataContractJsonSerializer串行器進行字典序列化/反序列化

我有一個結構,我去工作,發送到REST API,他們看起來像這樣:

{   "records": [ 
     { 
      "attributes": { 
       "OBJECTID": 1, 
       "Address": "380 New York St.", 
       "City": "Redlands", 
       "Region": "CA", 
       "Postal": "92373" 
      } 
     }, 
    { 
      "attributes": { 
       "OBJECTID": 2, 
       "Address": "1 World Way", 
       "City": "Los Angeles", 
       "Region": "CA", 
       "Postal": "90045" 
      } 
     } 
    ] 

我們所看到的是這樣的:

class SomeData 
{ 
    public List<SomeRecord> Records { get; set; } 
} 

class SomeRecord 
{ 
    public List<KeyValuePair<string, string>> Attributes { get; set; } 
} 

我如何歸因於我的對象,所以串行器可以產生這樣的結構?或者我應該創建包含每個屬性的屬性的對象?

問題是 - 此webservice似乎是屬性在這裏和那裏,我甚至不知道所有可能的名稱。所以,KVP名單似乎是一個不錯的選擇,但它對我無效。

回答

1

以下應該工作,

[DataContract] 
    [KnownType(typeof(Record))] 
    public class RecordList 
    { 
     public RecordList() 
     { 
      Records = new List<Record>(); 
     } 

     [DataMember] 
     public List<Record> Records { get; set; } 
    } 

    public class Record 
    { 
     public Record() 
     { 
      Attributes = new AttributeList(); 
     } 

     [DataMember] 
     public AttributeList Attributes { get; set; } 
    } 


    [Serializable] 
    public class AttributeList : DynamicObject, ISerializable 
    { 
     private readonly Dictionary<string, object> attributes = new Dictionary<string, object>(); 

     public override bool TrySetMember(SetMemberBinder binder, object value) 
     { 
      attributes[binder.Name] = value; 

      return true; 
     } 

     public void GetObjectData(SerializationInfo info, StreamingContext context) 
     { 
      foreach (var kvp in attributes) 
      { 
       info.AddValue(kvp.Key, kvp.Value); 
      } 
     } 
    } 


     [Test] 
     public void TestSerialize() 
     { 
      var holder = new RecordList(); 

      dynamic record = new Record(); 
      record.Attributes.OBJECTID = 1; 
      record.Attributes.Address = "380 New York St."; 
      record.Attributes.City = "Redlands"; 
      record.Attributes.Address = "Region"; 
      record.Attributes.Region = "CA"; 
      record.Attributes.Postal = "92373"; 

      holder.Records.Add(record); 

      var stream1 = new MemoryStream(); 
      var serializer = new DataContractJsonSerializer(typeof(RecordList)); 
      serializer.WriteObject(stream1, holder); 

      stream1.Position = 0; 
      StreamReader sr = new StreamReader(stream1); 
      Console.Write("JSON form of holder object: "); 
      Console.WriteLine(sr.ReadToEnd()); 
     } 
相關問題