Skip to content

Instantly share code, notes, and snippets.

@mattwcole
Last active July 26, 2018 09:29
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 mattwcole/f0db8dc307988e39571aacb29c42ec73 to your computer and use it in GitHub Desktop.
Save mattwcole/f0db8dc307988e39571aacb29c42ec73 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
namespace JsonFormat
{
public class Program
{
private const string InputData = @"{
""Directive"": ""S"",
""Wrapper"": [
{
""Field1"": ""Apple"",
""Field2"": ""Peach"",
""Field3"": ""@!!!@008d613d1ca60885468bf274daa693cc778430fc8a539bdf2e7dc2dec88cd922"",
""Field4"": ""Kiwi""
},
{
""Field1"": ""Apple2"",
""Field2"": ""Peach2"",
""Field3"": ""@!!!@17e9ad37968e25893e96855ba3d633e250a401a6584b2bc9c7288f9fc458a9b6"",
""Field4"": ""Kiwi2""
}
]
}";
private const string IntermediateResponse = @"{
""Wrapper"": [
{
""Token"": ""@!!!@17e9ad37968e25893e96855ba3d633e250a401a6584b2bc9c7288f9fc458a9b6"",
""Value"": ""test""
},
{
""Token"": ""@!!!@008d613d1ca60885468bf274daa693cc778430fc8a539bdf2e7dc2dec88cd922"",
""Value"": ""test2""
}
]
}";
public static void Main()
{
var inputData = JsonConvert.DeserializeObject<ItemsPayload>(InputData);
var propertiesLookup = new Dictionary<string, ItemUpdate>();
var propertiesRequest = new PropertySearchPayload {Wrapper = new List<PropertySearch>()};
foreach (var item in inputData.Wrapper)
foreach (var kvp in item.Where(property => property.Value.StartsWith("@!!!@")))
{
propertiesLookup[kvp.Value] = new ItemUpdate
{
Properties = item,
UpdateKey = kvp.Key
};
propertiesRequest.Wrapper.Add(new PropertySearch
{
Token = kvp.Value
});
}
var intermediateRequest = JsonConvert.SerializeObject(propertiesRequest, Formatting.Indented);
Console.WriteLine($"Built intermediate request payload:{Environment.NewLine}{intermediateRequest}");
var intermediateData = JsonConvert.DeserializeObject<PropertySearchPayload>(IntermediateResponse);
foreach (var item in intermediateData.Wrapper)
{
var itemToUpdate = propertiesLookup[item.Token];
itemToUpdate.Properties[$"@{itemToUpdate.UpdateKey}"] = item.Value;
}
var result = JsonConvert.SerializeObject(inputData, Formatting.Indented);
Console.WriteLine($"Built result:{Environment.NewLine}{result}");
}
public class ItemsPayload
{
public string Directive { get; set; }
public List<Dictionary<string, string>> Wrapper { get; set; }
}
public class PropertySearchPayload
{
public List<PropertySearch> Wrapper { get; set; }
}
public class PropertySearch
{
public string Token { get; set; }
public string Value { get; set; }
}
public class ItemUpdate
{
public Dictionary<string, string> Properties { get; set; }
public string UpdateKey { get; set; }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment