Created
February 20, 2018 00:32
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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