2011-06-17 50 views
4

我提出到返回JSO序列化對象,如該列表的役的電話:反序列化列表

{「員工」:[{「員工」:{」 ID「:」1「,」date_created「:」2011-06-16T15:03:27Z「,」extended「:[{」address「:{」street1「:」12345 first st。「,」city「丹佛「,」州「:」CO「}}]}},{」employee「:{」id「:」2「...

所以,你可以看到我第一次有員工名單對象稱爲員工。最重要的是,每個員工對象都包含另一個對象,稱爲擴展信息擴展(在這種情況下爲地址信息)。我想acheive是在整個列表傳遞作爲一個字符串來解串器,並取回一個列表與Employee對象看起來像這樣:

[Serializable] 
public class Employee { 
    public string Id { get; set; } 
    public string DateCreated { get; set; } 
    public ExtendedProperties Address { get; set; } 
} 

[Serializable] 
public class ExtendedProperties 
{ 
    public string Street1 { get; set; } 
    public string City { get; set; } 
    public string State { get; set; } 
} 

我發現使用NEwtonSoft類似的例子,但他們都不太在複合對象方面相同。如果需要,我可以刪除擴展屬性。但那會遠非理想。

任何幫助將不勝感激。

TIA!

回答

4

好了,這裏有幾件事情:

  • 你有一個外部「包裝」的一級或二級,映射employees財產屬性的實際徵收。你可以用一個單獨的類來處理它,或者使用LINQ to JSON來讀取整個東西,然後在反序列化集合之前在一層中挖掘。
  • 看起來你實際上得到了一個集合每個員工的擴展屬性,擴展屬性的一個屬性是地址。
  • 我不知道如何說服JSON庫轉換date_createdDateCreated,雖然我敢說它可以。

我砍死了東西可以讀這一點 - 但它是一個有點難看:

using System; 
using System.Collections.Generic; 
using System.IO; 

using Newtonsoft.Json; 

public class EmployeeCollection { 
    public List<EmployeeWrapper> Employees { get; set; } 
} 

public class EmployeeWrapper { 
    public Employee Employee { get; set; } 
} 

public class Employee { 
    public string Id { get; set; } 
    public string Date_Created { get; set; } 
    public List<ExtendedProperty> Extended { get; set; } 
} 

public class ExtendedProperty { 
    public Address Address { get; set; } 
} 

public class Address 
{ 
    public string Street1 { get; set; } 
    public string City { get; set; } 
    public string State { get; set; } 
} 

class Test 
{ 
    static void Main() 
    { 
     string json = @"{""employees"": 
      [{""employee"": 
       {""id"":""1"", 
       ""date_created"":""2011-06-16T15:03:27Z"", 
       ""extended"":[ 
        {""address"": 
        {""street1"":""12345 first st."", 
        ""city"":""Denver"", 
        ""state"":""CO""}}] 
       }}]}"; 


     var employees = 
      JsonConvert.DeserializeObject<EmployeeCollection>(json); 
     foreach (var employeeWrapper in employees.Employees) 
     { 
      Employee employee = employeeWrapper.Employee; 
      Console.WriteLine("ID: {0}", employee.Id); 
      Console.WriteLine("Date created: {0}", employee.Date_Created); 
      foreach (var prop in employee.Extended) 
      { 
       Console.WriteLine("Extended property:"); 
       Address addr = prop.Address; 
       Console.WriteLine("{0}/{1}/{2}", addr.Street1, 
            addr.City, addr.State); 
      } 
     } 
    }  
} 

如果你想保持你的原有類結構,我建議你使用LINQ到JSON做更手動的轉換。當你習慣了JSON庫時 - 特別是如果你對LINQ to Objects感到滿意時,這並不難。

+0

像往常一樣突出。正是我需要的。 – RockyMountainHigh

+0

爲什麼要構建一個'JsonSerializer'? – Jordan

+0

@Jordan:不知道爲什麼我這樣做 - 現在刪除:) –