CSharp · Console
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters;
using System.IO;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using NUnit.Framework; // Throws NUnit.Framework.AssertionException
//https://stackoverflow.com/questions/53636516/parse-json-without-declaring-model-class/53636937#53636937
public class Timeslot
{
public string room_id { get; set; }
public string room_name { get; set; }
public string booking_label { get; set; }
public DateTime booking_start { get; set; }
public DateTime booking_end { get; set; }
public DateTime booking_created { get; set; }
}
class TestClass
{
public static void Test()
{
var jsonResult = GetJson();
var reservations = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(jsonResult,
new { bookings =
new { group_id = default(string), name = default(string), url=default(string),
timeslots = default(List<Timeslot>) } });
Console.WriteLine("Populated reservations: ");
Console.WriteLine(JsonConvert.SerializeObject(reservations, Formatting.Indented));
Assert.IsTrue(reservations.bookings.group_id == (string)JToken.Parse(jsonResult).SelectToken("bookings.group_id"));
Assert.IsTrue(reservations.bookings.name == (string)JToken.Parse(jsonResult).SelectToken("bookings.name"));
Assert.IsTrue(reservations.bookings.url == (string)JToken.Parse(jsonResult).SelectToken("bookings.url"));
Assert.IsTrue(reservations.bookings.timeslots.Count == JToken.Parse(jsonResult).SelectTokens("bookings.timeslots[*]").Count());
}
static string GetJson()
{
var json = @"{
""bookings"": {
""group_id"": 123,
""name"": ""Study Rooms"",
""url"": ""My URL"",
""timeslots"": [{
// FIXED room_id changed to a string
""room_id"": ""0001"",
""room_name"": ""101"",
""booking_label"": ""Student 1"",
""booking_start"": ""2018-11-30T07:00:00-06:00"",
""booking_end"": ""2018-11-30T07:30:00-06:00"",
""booking_created"": ""2018-11-28T11:32:32-06:00""
}, {
""room_id"": ""0002"",
""room_name"": ""102"",
""booking_label"": ""Student 2"",
""booking_start"": ""2018-11-30T07:30:00-06:00"",
""booking_end"": ""2018-11-30T08:00:00-06:00"",
""booking_created"": ""2018-11-28T11:32:32-06:00""
}, //##AND many more like this##
]
}
}
";
return json;
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Environment version: " + Environment.Version);
Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine();
try
{
TestClass.Test();
}
catch (Exception ex)
{
Console.WriteLine("Failed with unhandled exception: ");
Console.WriteLine(ex);
throw;
}
}
}