-
-
Save bojanrajkovic/4748258 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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