Manu
Manu

Reputation: 35

Json.Net Mapping to Dictionary or somewhat else

Given this Json:

{
    "id": "1",
    "fields": [
        "a",
        "b",
        "c"
    ],
    "otherfields": [
        "n"
    ],
    "collection": {
        "element1": [
            {
                "7": {
                    "sub_id": "7",
                    "sub_name": "SN7"
                },
                "9": {
                    "sub_id": "9",
                    "sub_name": "SN9"
                }
            }
        ]
    }
}

and given the following classes:

public class Element
{
    [JsonProperty("sub_id")]
    public string SubId { get; set; }

    [JsonProperty("sub_name")]
    public string SubName { get; set; }
}

public class Element1
{
    [JsonProperty(?)] // <"7", Element> and <"9", Element> ???
    public IDictionary<String, Element> Elements { get; set; }
}

public class Collection
{
    [JsonProperty("element1")]
    public IList<Element1> Element1 { get; set; }
}

public class Example
{
    [JsonProperty("id")]
    public string Id { get; set; }

    [JsonProperty("fields")]
    public IList<string> Fields { get; set; }

    [JsonProperty("otherfields")]
    public IList<string> Otherfields { get; set; }

    [JsonProperty("collection")]
    public Collection Collection { get; set; }
}

Is it possible (and how?) to deserealize the json object to my given classes? or maybe, the best way to map the json object to another structure classes?,

Thank you in advance.

Upvotes: 0

Views: 131

Answers (1)

Moti Azu
Moti Azu

Reputation: 5442

You don't need Element1 - the element1 property in the json is an array with dictionaries.

public class Collection
{
    [JsonProperty("element1")]
    public IList<IDictionary<String, Element>> Element1 { get; set; }
}

Upvotes: 2

Related Questions