Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.NET: How to Serialize Nested Collections

Tags:

c#

json.net

This is driving me nuts... I am serializing a List to JSON using Json.net. I expect this JSON:

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

But instead I get this:

{
    "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
        }
    ]
}

The "values" collection I'd like as just a JSON array, but I can't for the life of me figure out how to get it to do this. I have a property on my "properties" objects called "values", so I understand why it's doing it, but I need just the straight array, not a JSON object.

like image 573
rjbullock Avatar asked Apr 22 '15 21:04

rjbullock


1 Answers

For that response, you need this class structure

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; }
}
like image 81
Aydin Avatar answered Oct 10 '22 14:10

Aydin