CSharp · Console
using System;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
string json = @"
{
""statistics"": [
{
""Strength"": {
""min"": 16,
""max"": 20
}
},
{
""Dexterity"": {
""min"": 16,
""max"": 20
}
}
]
}";
Container cont = JsonConvert.DeserializeObject<Container>(json);
foreach (Statistic stat in cont.Statistics)
{
Console.WriteLine(stat.Name + ": " + stat.Min + " - " + stat.Max);
}
}
}
public class Container
{
public Statistic[] Statistics { get; set; }
}
[JsonConverter(typeof(StatisticConverter))]
public class Statistic
{
public string Name { get; set; }
public int Min { get; set; }
public int Max { get; set; }
}
class StatisticConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Statistic);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
JProperty prop = jo.Properties().First();
Statistic stat = new Statistic
{
Name = prop.Name,
Min = (int)prop.Value["min"],
Max = (int)prop.Value["max"]
};
return stat;
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}