Skip to content

Instantly share code, notes, and snippets.

@Reizinixc
Created February 20, 2018 00:32
Show Gist options
  • Save Reizinixc/9c7131a8ee6a526e5483a8f4930fdcea to your computer and use it in GitHub Desktop.
Save Reizinixc/9c7131a8ee6a526e5483a8f4930fdcea to your computer and use it in GitHub Desktop.
Code for converting a specified JToken to the dictionary-based type. Best for use with LINQPad to read the information.
using System;
using System.Collections.ObjectModel;
using System.Linq;
using Newtonsoft.Json.Linq;
namespace Reizinixc.Common.Data.Json.Extensions
{
public static class JTokenExtensions
{
public static object ToImmutableObject(this JToken token)
{
if (token == null)
{
throw new ArgumentNullException(nameof(token));
}
switch (token.Type)
{
case JTokenType.Object:
{
return new ReadOnlyDictionary<string, object>(
token
.Children<JProperty>()
.ToDictionary(property => property.Name, property => property.Value.ToImmutableObject()));
}
case JTokenType.Array:
{
return token.Select(ToImmutableObject).ToList().AsReadOnly();
}
default:
{
return ((JValue)token).Value;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment