CSharp · Console
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Runtime.Serialization;
using System.Data;
using System.ComponentModel;
using System.Globalization;
using System.Collections.Specialized;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Net;
using System.Runtime.Serialization.Formatters;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
// https://stackoverflow.com/questions/43145603/json-data-not-converting-to-list
static class TestClass
{
public static void Test()
{
string inputJson = GetInitialJson();
string outputJson;
Console.WriteLine("Initial JSON: ");
Console.WriteLine(inputJson);
using (var inputStream = new MemoryStream(Encoding.UTF8.GetBytes(inputJson)))
using (var outputStream = new MemoryStream())
{
Func<string, string> typeNameMapper = (t) =>
{
if (!t.EndsWith(", Version=1.2.7.0, Culture=neutral, PublicKeyToken=null"))
t = t + ", Version=1.2.7.0, Culture=neutral, PublicKeyToken=null";
return t;
};
var paths = new[]
{
"channels.heart-rate.events",
"channels.location.events"
};
JsonExtensions.ReformatCollections(inputStream, outputStream, paths, typeNameMapper, Formatting.Indented);
outputStream.Position = 0;
outputJson = new StreamReader(outputStream).ReadToEnd();
}
Console.WriteLine("Output JSON: ");
Console.WriteLine(outputJson);
var expectedJson = GetExpectedJson();
Assert.IsTrue(JToken.DeepEquals(JToken.Parse(outputJson), JToken.Parse(expectedJson)));
Console.WriteLine("Output JSON and expected JSON are equivalent.");
}
static string GetInitialJson()
{
var json = @"{""channels"": {
""heart-rate"": {
""events"": {
""$type"": ""System.Collections.Generic.List`1[[Project.Model.Activity+Channel+Event, Project]], mscorlib"",
""$values"": [{
""$type"": ""Project.Model.ChannelEvents.HeartRateChannelEvent, Project"",
""beatsPerMinute"": 40,
""offset"": 0,
""Date"": ""2017-03-31T00:00:00.00-04:00"",
},null,{
""$type"": ""Project.Model.ChannelEvents.HeartRateChannelEvent, Project"",
""beatsPerMinute"": 40,
""offset"": 0,
""Date"": ""2017-03-31T00:00:00-04:00"",
}
]
}
},
""location"": {
""events"": {
""$type"": ""System.Collections.Generic.List`1[[Project.Model.Activity+Channel+Event, Project]], mscorlib"",
""$values"": [{
""$type"": ""Project.Model.ChannelEvents.LocationChannelEvent, Project"",
""latitude"": 0.0,
""longitude"": 0.0,
""offset"": 0
}
]
}
}
}}";
return json;
}
static string GetExpectedJson()
{
var json = @"{""channels"": {
""heart-rate"": {
""events"": {
""type"": ""Project.Model.ChannelEvents.HeartRateChannelEvent, Project, Version=1.2.7.0, Culture=neutral, PublicKeyToken=null"",
""structure"": [
""beatsPerMinute"",
""offset"",
""Date"",
],
""list"": [
[
40,
0,
""2017-03-31T00:00:00.00-04:00""
],
null,
[
40,
0,
""2017-03-31T00:00:00-04:00""
]
]
}
},
""location"": {
""events"": {
""type"": ""Project.Model.ChannelEvents.LocationChannelEvent, Project, Version=1.2.7.0, Culture=neutral, PublicKeyToken=null"",
""structure"": [
""latitude"",
""longitude"",
""offset""
],
""list"": [
[
0.0,
0.0,
0
]
]
}
}
}}";
return json;
}
}
public class AssertionFailedException : System.Exception
{
public AssertionFailedException() : base() { }
public AssertionFailedException(string s) : base(s) { }
}
public static class Assert
{
public static void IsTrue(bool value)
{
if (value == false)
throw new AssertionFailedException("failed");
}
}
public static class JsonExtensions
{
const string JsonTypeName = @"$type";
const string JsonValuesName = @"$values";
public static void ReformatCollections(Stream inputStream, Stream outputStream, IEnumerable<string> paths, Func<string, string> typeNameMapper, Formatting formatting)
{
var root = JToken.Load(new JsonTextReader(new StreamReader(inputStream)) { DateParseHandling = DateParseHandling.None });
root = ReformatCollections(root, paths, typeNameMapper);
var writer = new StreamWriter(outputStream);
var jsonWriter = new JsonTextWriter(writer) { Formatting = formatting };
root.WriteTo(jsonWriter);
jsonWriter.Flush();
writer.Flush();
}
public static JToken ReformatCollections(JToken root, IEnumerable<string> paths, Func<string, string> typeNameMapper)
{
foreach (var path in paths)
{
var token = root.SelectToken(path);
var newToken = token.ReformatCollection(typeNameMapper);
if (root == token)
root = newToken;
}
return root;
}
public static JToken ReformatCollection(this JToken value, Func<string, string> typeNameMapper)
{
if (value == null || value.Type == JTokenType.Null)
return value;
var array = value as JArray;
if (array == null)
array = value[JsonValuesName] as JArray;
if (array == null)
return value;
// Extract the item $type and ordered set of properties.
string type = null;
var properties = new Dictionary<string, int>();
foreach (var item in array)
{
if (item.Type == JTokenType.Null)
continue;
var obj = item as JObject;
if (obj == null)
throw new JsonSerializationException(string.Format("Item \"{0}\" was not a JObject", obj.ToString(Formatting.None)));
var objType = (string)obj[JsonTypeName];
if (objType != null && type == null)
type = objType;
else if (objType != null && type != null)
{
if (type != objType)
throw new JsonSerializationException("Too many item types.");
}
foreach (var property in obj.Properties().Where(p => p.Name != JsonTypeName))
{
if (!properties.ContainsKey(property.Name))
properties.Add(property.Name, properties.Count);
}
}
var propertyList = properties.OrderBy(p => p.Value).Select(p => p.Key).ToArray();
var newValue = new JObject();
if (type != null)
newValue["type"] = JToken.FromObject(typeNameMapper(type));
newValue["structure"] = JToken.FromObject(propertyList);
newValue["list"] = JToken.FromObject(array
.Select(o => (o.Type == JTokenType.Null ? o : propertyList.Where(p => o[p] != null).Select(p => o[p]))));
if (value.Parent != null)
value.Replace(newValue);
return newValue;
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Environment version: " + Environment.Version);
Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine("");
TestClass.Test();
}
}