CSharp · Console
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
public class Program
{
public static void Main()
{
string json = "{\"`LCA0001\": {\"23225007190002\": \"1\",\"23249206670003\": \"1\",\"01365100070018\": \"5\"},\"`LCA0003\": {\"23331406670018\": \"1\",\"24942506670004\": \"1\"},\"`LCA0005\": {\"01365100070018\": \"19\"}}";
Console.WriteLine(json);
Console.WriteLine();
//This works
Console.Write("Deserialize without class");
var root = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, int>>>(json);
foreach (var locationKvp in root)
{
foreach (var skuKvp in locationKvp.Value)
{
Console.WriteLine("location: " + locationKvp.Key + ", sku: " + skuKvp.Key + ", qty: " + skuKvp.Value);
}
}
// Create an InventoryLocations object using the deserialized data from the original Json
InventoryLocations locations = new InventoryLocations {InventoryLocation = root};
// Create a new JsonSerializerSettings that utilizes the ContractResolver
var settings = new JsonSerializerSettings {ContractResolver = new DictionaryAsArrayResolver()};
// Serialize our InventoryLocations object into the new Json format with the ContractResolver
string json2 = JsonConvert.SerializeObject(locations, settings);
Console.WriteLine();
Console.WriteLine(json2);
//This works now
Console.Write("\nDeserialize with class");
// Deserialize an InventoryLocations using the JsonSerializerSettings that uses the ContractResolver
var root2 = JsonConvert.DeserializeObject<InventoryLocations>(json2, settings);
foreach (var locationKvp in root2.InventoryLocation)
{
foreach (var skuKvp in locationKvp.Value)
{
Console.WriteLine("location: " + locationKvp.Key + ", sku: " + skuKvp.Key + ", qty: " + skuKvp.Value);
}
}
}
}
class InventoryLocations
{
public Dictionary<string, Dictionary<string, int>> InventoryLocation { get; set; }
}
class DictionaryAsArrayResolver : DefaultContractResolver
{
protected override JsonContract CreateContract(Type objectType)
{
if (objectType.GetInterfaces().Any(i => i == typeof(IDictionary) || (i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDictionary<,>))))
{
return base.CreateArrayContract(objectType);
}
return base.CreateContract(objectType);
}
}