6

I would like to desierialze the json from here.

Similar to this:

{
"BW": {
    "Neujahrstag": {
        "datum": "2017-01-01",
        "hinweis": ""
    },
    "Heilige Drei K\u00f6nige": {
        "datum": "2017-01-06",
        "hinweis": ""
    },
    "Gr\u00fcndonnerstag": {
        "datum": "2017-04-13",
        "hinweis": "Gem\u00e4\u00df \u00a7 4 Abs. 3 des Feiertagsgesetzes von Baden-W\u00fcrttemberg[10] haben Sch\u00fcler am Gr\u00fcndonnerstag und am Reformationstag schulfrei. In der Regel legt das Kultusministerium die Ferientermine so fest, dass diese beiden Tage in die Osterferien bzw. in die Herbstferien fallen."
    },
    "Karfreitag": {
        "datum": "2017-04-14",
        "hinweis": ""
    }
},
"BY": {
    "Neujahrstag": {
        "datum": "2017-01-01",
        "hinweis": ""
    },
    "Heilige Drei K\u00f6nige": {
        "datum": "2017-01-06",
        "hinweis": ""
    }
}

}

I would like to deserialize into this:

public class Root
{
    public State[] States { get; set; }
}

public class State
{        
    public Holiday[] Holidays { get; set; }
}

public class Holiday
{
    public DateTime Date { get; set; }
    public string Note { get; set; }
}

But since the propertynames are not fixed I am not able to do this.

I've also tried using JObject.Parse() but that did not help me alot.

Any idea on how to do this ?

Felix D.
  • 4,811
  • 8
  • 38
  • 72

2 Answers2

9

If you modify your model to this:

public class Root : Dictionary<string, State> { }

public class State : Dictionary<string, Holiday> { }

public class Holiday {
    [JsonProperty(PropertyName = "datum")]
    public DateTime Date { get; set; }

    [JsonProperty(PropertyName = "hinweis")]
    public string Note { get; set; }
}

You can deserialize using this:

var root = JsonConvert.DeserializeObject<Root>(str);
var firstBwHoliday = root["BW"]?["Neujahrstag"].Date;
K. H.
  • 208
  • 1
  • 5
3

First update the Holiday to handle the property names

public class Holiday {
    [JsonProperty("datum")]
    public DateTime Date { get; set; }
    [JsonProperty("hinweis")]
    public string Note { get; set; }
}

Next you want to deserialize to nested Dictionaries

var rawRoot = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, Holiday>>>(json);

Finally you want to traverse the dictionaries to get your final result

var root = new Root {
    States = rawRoot.Select(stateKvp => new State() {
        Holidays = stateKvp.Value.Select(holidayKvp => holidayKvp.Value).ToArray()
    })
    .ToArray()
};

You do however loose the keys as they were not part of your final model.

Nkosi
  • 235,767
  • 35
  • 427
  • 472