user3024750 user3024750 - 2 months ago 11
C# Question

Json.NET - format an array of objects with names

I have an array like this

...
Is there any way to format something like this in a List? I tried to do it but he always stops at the 21460106 number. Also tried json2csharp but that only makes 5000 classes where every class has the number as its name.

dbc dbc
Answer

Your outer JSON container isn't an array, it's a JSON object: a comma-delimited set of name/value pairs surrounded by braces. Since the names are arbitrary keys and not fixed, the easiest way to deserialize this is as a dictionary.

Types:

public class PLATFORM
{
    public string LINIE { get; set; }
    public string ECHTZEIT { get; set; }
    public string VERKEHRSMITTEL { get; set; }
    public string RBL_NUMMER { get; set; }
    public string BEREICH { get; set; }
    public string RICHTUNG { get; set; }
    public string REIHENFOLGE { get; set; }
    public string STEIG { get; set; }
    public string STEIG_WGS84_LAT { get; set; }
    public string STEIG_WGS84_LON { get; set; }
}

public class RootObject
{
    public string HALTESTELLEN_ID { get; set; }
    public string TYP { get; set; }
    public string DIVA { get; set; }
    public string NAME { get; set; }
    public string GEMEINDE { get; set; }
    public string GEMEINDE_ID { get; set; }
    public string WGS84_LAT { get; set; }
    public string WGS84_LON { get; set; }
    public string STAND { get; set; }
    public List<PLATFORM> PLATFORMS { get; set; }
    public List<string> LINES { get; set; }
}

Deserialization code:

var dict = JsonConvert.DeserializeObject<Dictionary<long, RootObject>>(json);

I chose long as the key type since all of your root property names look to be integral strings. You could use Dictionary<string, RootObject> if not.

To generate the RootObject class I copied the JSON from one of the values in the root object -- the value of "214460106" in this case -- to http://json2csharp.com/.

Sample fiddle.

For related documentation see: Deserialize a Dictionary.

Comments