Skip to content

Instantly share code, notes, and snippets.

@MelbourneDeveloper
Created June 24, 2021 08:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MelbourneDeveloper/21fe81e4972dbc7c9a89b3534151cfd0 to your computer and use it in GitHub Desktop.
Save MelbourneDeveloper/21fe81e4972dbc7c9a89b3534151cfd0 to your computer and use it in GitHub Desktop.
Converts Json to a Json Object (ImmutableDictionary<string, JsonValue>)
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
#pragma warning disable format
#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type.
#pragma warning disable CS8604 // Possible null reference argument.
namespace JsonDataStructure
{
public static class JsonExtensions
{
public static ImmutableDictionary<string, JsonValue> ToJsonObject(this string json)
{
var deserializedObject = (JObject)JsonConvert.DeserializeObject(json);
return ProcessObject(deserializedObject).ToImmutableDictionary();
}
private static Dictionary<string, JsonValue> ProcessObject(JObject deserializedObject)
{
var jsonObject = new Dictionary<string, JsonValue>();
foreach (var property in deserializedObject.Properties())
{
ProcessProperty(jsonObject, property);
}
return jsonObject;
}
private static void ProcessProperty(Dictionary<string, JsonValue> jsonObject, JProperty property)
{
switch (property.Value.Type)
{
case JTokenType.String:
jsonObject.Add(property.Name, new JsonValue((string)property.Value));
break;
case JTokenType.None:
throw new NotImplementedException();
case JTokenType.Object:
jsonObject.Add(property.Name, new JsonValue(ProcessObject((JObject)property.Value).ToImmutableDictionary()));
break;
case JTokenType.Array:
var children = new List<JsonValue>();
foreach(var token in property.Value.Children())
{
if (token is JValue value)
{
children.Add(value.Value!=null? new JsonValue(value.Value<decimal>()): new JsonValue());
}
else
{
var childJsonObject = new Dictionary<string, JsonValue>();
foreach (JProperty childProperty in token.Children())
{
ProcessProperty(childJsonObject, childProperty);
}
children.Add(new JsonValue(childJsonObject.ToImmutableDictionary()));
}
}
jsonObject.Add(property.Name, new JsonValue(children.ToImmutableList()));
break;
case JTokenType.Integer:
jsonObject.Add(property.Name, new JsonValue((int)property.Value));
break;
case JTokenType.Constructor:
case JTokenType.Property:
case JTokenType.Comment:
case JTokenType.Float:
case JTokenType.Boolean:
case JTokenType.Null:
case JTokenType.Undefined:
case JTokenType.Date:
case JTokenType.Raw:
case JTokenType.Bytes:
case JTokenType.Guid:
case JTokenType.Uri:
case JTokenType.TimeSpan:
default:
throw new NotImplementedException();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment