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/39461518/c-sharp-json-net-deserialize-response-that-uses-an-unusual-data-structure/
// Related: https://dotnetfiddle.net/9Sw9Sw
// Related: https://dotnetfiddle.net/gBPm2g
public class ObjectToArrayConverter<T> : JsonConverter
{
//https://stackoverflow.com/a/39462464/3744182
public override bool CanConvert(Type objectType)
{
return typeof(T) == objectType;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var objectType = value.GetType();
var contract = serializer.ContractResolver.ResolveContract(objectType) as JsonObjectContract;
if (contract == null)
throw new JsonSerializationException(string.Format("invalid type {0}.", objectType.FullName));
writer.WriteStartArray();
foreach (var property in SerializableProperties(contract))
{
var propertyValue = property.ValueProvider.GetValue(value);
if (property.Converter != null && property.Converter.CanWrite)
property.Converter.WriteJson(writer, propertyValue, serializer);
else
serializer.Serialize(writer, propertyValue);
}
writer.WriteEndArray();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var contract = serializer.ContractResolver.ResolveContract(objectType) as JsonObjectContract;
if (contract == null)
throw new JsonSerializationException(string.Format("invalid type {0}.", objectType.FullName));
if (reader.MoveToContentAndAssert().TokenType == JsonToken.Null)
return null;
if (reader.TokenType != JsonToken.StartArray)
throw new JsonSerializationException(string.Format("token {0} was not JsonToken.StartArray", reader.TokenType));
// Not implemented: JsonObjectContract.CreatorParameters, serialization callbacks,
existingValue = existingValue ?? contract.DefaultCreator();
using (var enumerator = SerializableProperties(contract).GetEnumerator())
{
while (true)
{
switch (reader.ReadToContentAndAssert().TokenType)
{
case JsonToken.EndArray:
return existingValue;
default:
if (!enumerator.MoveNext())
{
reader.Skip();
break;
}
var property = enumerator.Current;
object propertyValue;
// TODO:
// https://www.newtonsoft.com/json/help/html/Properties_T_Newtonsoft_Json_Serialization_JsonProperty.htm
// JsonProperty.ItemConverter, ItemIsReference, ItemReferenceLoopHandling, ItemTypeNameHandling, DefaultValue, DefaultValueHandling, ReferenceLoopHandling, Required, TypeNameHandling, ...
if (property.Converter != null && property.Converter.CanRead)
propertyValue = property.Converter.ReadJson(reader, property.PropertyType, property.ValueProvider.GetValue(existingValue), serializer);
else
propertyValue = serializer.Deserialize(reader, property.PropertyType);
property.ValueProvider.SetValue(existingValue, propertyValue);
break;
}
}
}
}
static IEnumerable<JsonProperty> SerializableProperties(JsonObjectContract contract)
{
return contract.Properties.Where(p => !p.Ignored && p.Readable && p.Writable);
}
}
public static partial class JsonExtensions
{
public static JsonReader ReadToContentAndAssert(this JsonReader reader)
{
return reader.ReadAndAssert().MoveToContentAndAssert();
}
public static JsonReader MoveToContentAndAssert(this JsonReader reader)
{
if (reader == null)
throw new ArgumentNullException();
if (reader.TokenType == JsonToken.None) // Skip past beginning of stream.
reader.ReadAndAssert();
while (reader.TokenType == JsonToken.Comment) // Skip past comments.
reader.ReadAndAssert();
return reader;
}
public static JsonReader ReadAndAssert(this JsonReader reader)
{
if (reader == null)
throw new ArgumentNullException();
if (!reader.Read())
throw new JsonReaderException("Unexpected end of JSON stream.");
return reader;
}
}
[JsonConverter(typeof(ObjectToArrayConverter<Player>))]
public class Player
{
public string ShortPlayerDescription { get { return ""; } }
[JsonIgnore]
public string IgnoreMe2 { get; set; }
[JsonProperty(Order = 1)]
public int UniqueID { get; set; }
[JsonProperty(Order = 2)]
public string PlayerDescription { get; set; }
// Other fields as required.
}
public class ScoreboardResults
{
public int timestamp { get; set; }
public int total_players { get; set; }
public int max_score { get; set; }
public Dictionary<string, Player> players { get; set; }
}
class TestClass
{
static string GetJson()
{
var json = @"{
""timestamp"": 1473730993,
""total_players"": 945,
""max_score"": 8961474,
""players"": {
""Player1Username"": [
121,
""somestring"",
679900,
5,
4497,
""anotherString"",
""thirdString"",
""fourthString"",
123,
22,
""YetAnotherString""],
""Player2Username"": [
886,
""stillAstring"",
1677,
1,
9876,
""alwaysAstring"",
""thirdString"",
""fourthString"",
876,
77,
""string""]
}
}";
return json;
}
internal static void Test()
{
var inputJson = GetJson();
Console.WriteLine("Input JSON: ");
Console.WriteLine(JToken.Parse(inputJson));
var root = JsonConvert.DeserializeObject<ScoreboardResults>(inputJson);
var json2 = JsonConvert.SerializeObject(root, Formatting.Indented);
Console.WriteLine("\nOutput JSON: ");
Console.WriteLine(json2);
var root2 = JsonConvert.DeserializeObject<ScoreboardResults>(json2);
var json3 = JsonConvert.SerializeObject(root2, Formatting.Indented);
Assert.IsTrue(json2 == json3);
Assert.IsTrue(JToken.Parse(inputJson)
.SelectTokens("players.*")
.Cast<JArray>()
.Zip(JToken.Parse(json3)
.SelectTokens("players.*")
.Cast<JArray>(),
(a1, a2) => a1.Count >= a2.Count && a1.Zip(a2, (i1, i2) => JToken.DeepEquals(i1, i2)).All(b => b))
.All(b => b));
// Assert that trying to deserialize truncated files always throws.
for (int i = 1; i < json3.Length - 1; i++)
{
Assert.Throws(Is.InstanceOf(typeof(JsonException)), () => JsonConvert.DeserializeObject<ScoreboardResults>(json3.Substring(i, json3.Length - i)));
}
}
}
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;
}
}
}