CSharp · Console
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
string json = @"
{
""name"": ""Example"",
""description"": ""Example JSON"",
""properties"": {
""foo"": ""bar"",
""foo1"": ""bar2"",
""foo3"": ""bar4""
},
""stages"": {
""This is a stage"": {
""stageInfo1"": ""some info"",
""stageInfo2"": ""more info"",
""integration"": {
""x"": ""x1"",
""y"": ""y2"",
""z"": ""z3"",
""definition"": []
}
},
""Another Stage"": {
""stageInfo1"": ""info here"",
""stageInfo2"": ""info there"",
""integration"": {
""x"": ""x4"",
""y"": ""y5"",
""z"": ""z6"",
""definition"": {
""5a4d7de4c6518"": {
""Editable"": true,
""ID"": ""5a4d7de4c6518"",
""Name"": ""My example""
}
}
}
}
}
}";
RootObject obj = JsonConvert.DeserializeObject<RootObject>(json);
foreach (var kvp in obj.stages)
{
Console.WriteLine("---" + kvp.Key + "---");
var stage = kvp.Value;
var definition = stage.integration.definition;
if (definition.Count > 0)
{
foreach (var def in definition.Values)
{
Console.WriteLine("ID: " + def.ID);
Console.WriteLine("Name: " + def.Name);
Console.WriteLine("Editable: " + def.Editable);
}
}
else
{
Console.WriteLine("(empty dictionary)");
}
Console.WriteLine();
}
}
}
public class RootObject
{
public string name { get; set; }
public string description { get; set; }
public Dictionary<string, string> properties { get; set; }
public Dictionary<string, Stage> stages { get; set; }
}
public class Stage
{
public string stageInfo1 { get; set; }
public string stageInfo2 { get; set; }
public Integration integration { get; set; }
}
public class Integration
{
public string x { get; set; }
public string y { get; set; }
public string z { get; set; }
[JsonConverter(typeof(TolerantObjectConverter<Dictionary<string, Definition>>))]
public Dictionary<string, Definition> definition { get; set; }
}
public class Definition
{
public bool Editable { get; set; }
public string ID { get; set; }
public string Name { get; set; }
}
class TolerantObjectConverter<T> : JsonConverter where T: new()
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(T);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
object result = new T();
if (token.Type == JTokenType.Object)
{
serializer.Populate(token.CreateReader(), result);
}
return result;
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}