Skip to content

Instantly share code, notes, and snippets.

@bojanrajkovic
Forked from chkn/JSON.cs
Last active December 12, 2015 08:59
Show Gist options
  • Save bojanrajkovic/4748258 to your computer and use it in GitHub Desktop.
Save bojanrajkovic/4748258 to your computer and use it in GitHub Desktop.
using System;
using System.Linq;
using System.Reflection;
public static class JSON
{
public static string Stringify (object obj)
{
if (obj == null) return "null";
if (obj is ValueType) return obj.ToString ().ToLowerInvariant ();
if (obj is string) return System.Text.RegularExpressions.Regex.Escape (obj as string);
// assume it's a POCO
return "{" + string.Join (",",
from p in obj.GetType ().GetProperties ()
let json = (JSONAttribute) p.GetCustomAttributes (typeof (JSONAttribute), true).FirstOrDefault ()
where json != null && !p.IsSpecialName
select string.Format (@"""{0}"":{1}", json.Key ?? p.Name, Stringify (p.GetValue (obj, null)))
) + "}";
}
}
public class JSONAttribute : Attribute
{
public string Key { get; set; }
public JSONAttribute () {}
public JSONAttribute (string key) { Key = key; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment