Skip to content

Instantly share code, notes, and snippets.

@gnab
Created January 23, 2012 07:40
Show Gist options
  • Save gnab/1661423 to your computer and use it in GitHub Desktop.
Save gnab/1661423 to your computer and use it in GitHub Desktop.
C# JSON Stuff
abstract class Object<T>
{
private readonly List<T> _properties;
protected abstract string FormatString { get; }
protected Object(params T[] properties)
{
_properties = new List<T>(properties);
}
public void Add(T item)
{
_properties.Add(item);
}
public static implicit operator string(Object<T> obj)
{
return obj.ToString();
}
public override string ToString()
{
return string.Format(FormatString, string.Join(",", _properties.Select(p => p.ToString())));
}
}
class Object : Object<Property>
{
public Object(params Property[] properties) : base(properties) {}
protected override string FormatString
{
get { return "{{{0}}}"; }
}
}
class Array : Object<Object>
{
public Array(params Object[] elements) : base(elements) {}
protected override string FormatString
{
get { return "[{0}]"; }
}
}
class Property
{
private readonly string _name;
private readonly object _value;
public Property(string name, object value)
{
_name = name;
_value = value is string ? "\"" + value + "\"" : value;
}
public override string ToString()
{
return string.Format("\"{0}\":{1}", _name, _value);
}
public static implicit operator string(Property property)
{
return property.ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment