by Bar Zohan
26. October 2010 22:41
Beside parsing all other object types, DateTime parsing from JSON had been a great headache. As I did not need it for the current project I've just ignored DateTime typed attributes of JSON [pi.PropertyType != typeof(DateTime) :)]
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Json;
using System.Reflection;
using System.Collections;
namespace Json
{
public static class JsonHelper
{
public static T ParseObject<T>(JsonValue jsonObject)
{
T result = (T) Activator.CreateInstance(typeof(T));
foreach (PropertyInfo pi in result.GetType().GetProperties())
{
if (jsonObject.ContainsKey(pi.Name))
{
JsonValue jsonPrimitive = jsonObject[pi.Name];
if (pi.PropertyType != typeof(DateTime))
{
object o = Convert.ChangeType(jsonPrimitive.ToString(), pi.PropertyType, new FakeFormatProvider());
if (o is string)
{
o = (o as string).Replace("\"", "");
}
pi.SetValue(result, o, null);
}
}
}
return result;
}
public static string ToJson(this object obj)
{
string result = "";
if (obj is IList)
{
result = "[";
IList objList = (IList)obj;
for (int i = 0; i < objList.Count; i++)
{
result += objList[i].ToJson().ToString();
if (i != objList.Count -1)
{
result += ",";
}
}
result += "]";
}
else if (obj is int || obj is Int32 || obj is Int16 || obj is Int64)
{
result = obj.ToString();
}
else if (obj is string)
{
result = "\"" + obj.ToString() + "\"";
}
else
{
result = "{";
for (int i = 0; i < obj.GetType().GetProperties().Length; i++)
{
PropertyInfo pi = obj.GetType().GetProperties()[i];
result += "\"" + pi.Name + "\":" + pi.GetValue(obj, null).ToJson();
if (i != obj.GetType().GetProperties().Length - 1)
{
result += ",";
}
}
result += "}";
}
return result;
}
}
public class FakeFormatProvider : IFormatProvider
{
public object GetFormat(Type formatType)
{
return null;
}
}
}