Skip to content

Instantly share code, notes, and snippets.

@ebdrup
Created March 10, 2013 17:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ebdrup/5129451 to your computer and use it in GitHub Desktop.
Save ebdrup/5129451 to your computer and use it in GitHub Desktop.
JSON mixin like underscore extend for dotNet (works on JSON strings not Objects). Relies on Newtonsoft.Json from http://json.net
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Newtonsoft.Json;
namespace CopenhagenCode
{
public class JSON
{
public static string Mixin(string json1, string json2)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
var writtenValues = new Dictionary<string,bool>();
using (JsonWriter writer = new JsonTextWriter(sw))
{
writer.Formatting = Formatting.None;
writer.WriteStartObject();
writeJson(writer, json2, writtenValues);
writeJson(writer, json1, writtenValues);
writer.WriteEndObject();
}
return sb.ToString();
}
static private void writeJson(JsonWriter writer, string json, Dictionary<string, bool> writtenValues)
{
JsonTextReader reader = new JsonTextReader(new StringReader(json));
var objectDepth = 0;
var writeProperty = true;
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
if (objectDepth == 1)
{
var propertyName = (string)reader.Value;
if (writtenValues.ContainsKey(propertyName))
{
writeProperty = false; //do not write properties on depth 0 that are already written
}
else
{
writtenValues[propertyName] = true;
writeProperty = true;
}
}
if (writeProperty)
{
writer.WriteToken(reader);
}
break;
case JsonToken.EndObject:
objectDepth--;
if (objectDepth == 0)
{
return;
}
if (writeProperty)
{
writer.WriteEndObject();
}
break;
case JsonToken.StartObject:
if (objectDepth != 0 && writeProperty)
{
writer.WriteStartObject();
}
objectDepth++;
break;
default:
if (writeProperty)
{
writer.WriteToken(reader);
}
break;
}
}
}
}
}
@ianflitman
Copy link

I am thinking of using JSON.NET for REST calls. However, I really like the mixins of Jackson that use annotations to build class objects from the JSON payload. Can I use this class for that or does it have another way of doing things? Perhaps could you write a simple client class to show how this mixin is used.

@ebdrup
Copy link
Author

ebdrup commented Aug 27, 2013

It works like underscores .extend method, except it works on JSON strings and outputs a JSON string. Does not build any objects, just strings.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment