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/58477749/json-deserialize-mapping-array-to-their-own-property
public class Product
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("sku")]
public string SKU { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("ship_length")]
public decimal ShipLength { get; set; }
[JsonProperty("ship_width")]
public decimal ShipWidth { get; set; }
[JsonProperty("ship_height")]
public decimal ShipHeight { get; set; }
}
public class CustomAttributeObjectConverter<T> : JsonConverter<T> where T : new()
{
public override T ReadJson(JsonReader reader, Type objectType, T existingValue, bool hasExistingValue, JsonSerializer serializer)
{
var obj = JToken.Load(reader).ToJTokenType<JObject>();
if (obj == null)
return (T)(object)null;
var attributes = obj["custom_attributes"].RemoveFromLowestPossibleParent().ToJTokenType<JObject>();
if (attributes != null)
{
foreach (var item in attributes.PropertyValues().OfType<JObject>())
{
var name = (string)item["attribute_code"];
if (name != null)
obj.Add(name, item["value"]);
}
}
if (!hasExistingValue)
existingValue = (T)serializer.ContractResolver.ResolveContract(objectType).DefaultCreator();
using (var tokenReader = obj.CreateReader())
serializer.Populate(tokenReader, existingValue);
return existingValue;
}
public override void WriteJson(JsonWriter writer, T value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanWrite { get { return false; } }
}
public static partial class JsonExtensions
{
public static TJToken ToJTokenType<TJToken>(this JToken item) where TJToken : JToken
{
var result = item as TJToken;
if (item != null)
return result;
if (item == null || item.Type == JTokenType.Null)
return null;
throw new JsonException(string.Format("Cannot cast {0} to {1}", item.Type, typeof(TJToken)));
}
public static JToken RemoveFromLowestPossibleParent(this JToken node)
{
if (node == null)
return null;
// If the parent is a JProperty, remove that instead of the token itself.
var contained = node.Parent is JProperty ? node.Parent : node;
contained.Remove();
// Also detach the node from its immediate containing property -- Remove() does not do this even though it seems like it should
if (contained is JProperty)
((JProperty)node.Parent).Value = null;
return node;
}
}
class TestClass
{
public static void Test()
{
var json = GetJson();
var settings = new JsonSerializerSettings
{
Converters = { new CustomAttributeObjectConverter<Product>() },
};
var product = JsonConvert.DeserializeObject<Product>(json, settings);
var json2 = JsonConvert.SerializeObject(product, Formatting.Indented, settings);
Console.WriteLine(json2);
Assert.IsTrue(product.ShipLength == (decimal)JToken.Parse(json).SelectToken("..custom_attributes..[?(@.attribute_code == 'ship_length')].value"));
Assert.IsTrue(product.ShipHeight == (decimal)JToken.Parse(json).SelectToken("..custom_attributes..[?(@.attribute_code == 'ship_height')].value"));
Assert.IsTrue(product.ShipWidth == (decimal)JToken.Parse(json).SelectToken("..custom_attributes..[?(@.attribute_code == 'ship_width')].value"));
}
static string GetJson()
{
var json = @"{
""id"":121,
""sku"":""008MBLU"",
""name"":""Pillow Covers - King Mauve (2-pack)"",
""custom_attributes"":{
""11"":{
""attribute_code"":""ship_length"",
""value"":""11.0000""
},
""16"":{
""attribute_code"":""ship_width"",
""value"":""7.0000""
},
""19"":{
""attribute_code"":""ship_height"",
""value"":""1.0000""
}
}
}
";
return json;
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
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;
}
}
public static string GetNetCoreVersion()
{
//https://techblog.dorogin.com/how-to-detect-net-core-version-in-runtime-ecd65ad695be
//
var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
var assemblyPath = assembly.CodeBase.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];
return null;
}
}