2015-04-22 102 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