CSharp · Console
using System;
using Newtonsoft.Json;
using System.Linq;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var AvailabilityMap = JsonConvert.DeserializeObject<Station[]>(json, new StationConverter());
Console.WriteLine(AvailabilityMap[0].NearbyStations[0]);
}
public class StationConverter : JsonConverter
{
public override void WriteJson(JsonWriter w, object v, JsonSerializer s)
{
throw new NotImplementedException("Unnecessary: CanWrite is false.");
}
public override object ReadJson(JsonReader r, Type t, object v, JsonSerializer s)
{
// Load JObject from stream
JObject jObject = JObject.Load(r);
// convert your csv string into a proper array
// by wrapping it in square brackets
// and then reset your property
var prop = jObject.Property("nearbyStations");
var wrapped = string.Format("[{0}]", prop.Value);
JArray jsonArray = JArray.Parse(wrapped);
prop.Value = jsonArray;
// Create target object
var target = new Station();
// Populate the object properties
s.Populate(jObject.CreateReader(), target);
return target;
}
public override bool CanWrite
{
get
{
return false;
}
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof (Station);
}
}
private static string json = @"
[
{
""id"": ""1"",
""district"": ""1"",
""lon"": ""4.420650000000000000"",
""lat"": ""51.21782000000000000"",
""bikes"": ""19"",
""slots"": ""14"",
""zip"": ""2018"",
""address"": ""Koningin Astridplein"",
""addressNumber"": null,
""nearbyStations"": ""3,4,5,24"",
""status"": ""OPN"",
""name"": ""001- Centraal Station - Astrid""
},
{
""id"": ""1"",
""district"": ""1"",
""lon"": ""4.420650000000000000"",
""lat"": ""51.21782000000000000"",
""bikes"": ""19"",
""slots"": ""14"",
""zip"": ""2018"",
""address"": ""Koningin Astridplein"",
""addressNumber"": null,
""nearbyStations"": ""3,4,5,24"",
""status"": ""OPN"",
""name"": ""001- Centraal Station - Astrid""
}
]
";
}
public class Station
{
public int Id
{
get;
set;
}
public double Lon
{
get;
set;
}
public double Lat
{
get;
set;
}
public int Bikes
{
get;
set;
}
public int Slots
{
get;
set;
}
public string Address
{
get;
set;
}
public int[] NearbyStations
{
get;
set;
}
public string Status
{
get;
set;
}
public string Name
{
get;
set;
}
}