2015-04-22 97 views
3

這使我瘋狂......我使用Json.net序列化List到JSON。我希望這個JSON:JSON.NET:如何序列化嵌套集合

{ 
    "fieldsets": [ 
     { 
      "properties": [ 
       { 
        "alias": "date", 
        "value": "2014-02-12T00:00:00" 
       }, 
       { 
        "alias": "time", 
        "value": null 
       } 
      ], 
      "alias": "eventDates", 
      "disabled": false 
     } 
    ] 
} 

而是我得到這個:

{ 
    "fieldsets": [ 
     { 
      "properties": [ 
       { 
        "values": [ 
         { 
          "alias": "date", 
          "value": "2014-07-13T00:00:00" 
         }, 
         { 
          "alias": "time", 
          "value": "Registration begins at 8:00 AM; walk begins at 9:00 AM" 
         } 
        ] 
       } 
      ], 
      "alias": "eventDates", 
      "disabled": false 
     } 
    ] 
} 

的「價值觀」收集我像只是一個JSON數組,但我不能爲我的生活弄清楚如何讓它做到這一點。我在我的「屬性」對象上有一個名爲「值」的屬性,所以我理解它爲什麼這樣做,但我只需要直接數組,而不是JSON對象。

+2

讓我們來看看爲你序列化對象的對象定義。 – OneHoopyFrood

+2

http://json2csharp.com/去野外 –

回答

7

對於這種反應,你需要這個階級結構

public class Property 
{ 
    [JsonProperty("alias")] 
    public string Alias { get; set; } 

    [JsonProperty("value")] 
    public string Value { get; set; } 
} 

public class Fieldset 
{ 
    [JsonProperty("properties")] 
    public Property[] Properties { get; set; } 

    [JsonProperty("alias")] 
    public string Alias { get; set; } 

    [JsonProperty("disabled")] 
    public bool Disabled { get; set; } 
} 

public class Response 
{ 
    [JsonProperty("fieldsets")] 
    public Fieldset[] Fieldsets { get; set; } 
} 
+0

這是非常接近,除了我回到「屬性」陣列奇怪的東西......它輸出兩次,一次用「屬性」和一次用「屬性」: – rjbullock

+0

沒關係......我在錯誤的地方有一個JsonProperty屬性......這有效!非常感謝!!!花了幾乎整整一天的時間試圖讓這個權利。 : -/ – rjbullock

+0

很高興我能夠幫助:) –

0

這可能是答案:

public class Property 
{ 
    public string alias { get; set; } 
    public string value { get; set; } 
} 

public class Fieldset 
{ 
    public List<Property> properties { get; set; } 
    public string alias { get; set; } 
    public bool disabled { get; set; } 
} 

public class RootObject 
{ 
    public List<Fieldset> fieldsets { get; set; } 
} 
+2

你剛發佈json2csharp.com給你什麼? – OneHoopyFrood

+0

那麼,有一件事你不能在列表上使用默認的get/set,但這是一個開始。 – rjbullock

+0

ahhaha謝謝@rjbullock,但依然如此。 – xsami