ln.json/mapping/JSONObjectMapping.cs

63 lines
2.3 KiB
C#

// /**
// * File: JSONObjectMapping.cs
// * Author: haraldwolff
// *
// * This file and it's content is copyrighted by the Author and / or copyright holder.
// * Any use wihtout proper permission is illegal and may lead to legal actions.
// *
// *
// **/
using System;
using System.Collections.Generic;
using System.Reflection;
namespace ln.json.mapping
{
public class JSONObjectMapping : JSONMapping
{
Dictionary<string, Action<object,object>> setters = new Dictionary<string, Action<object,object>>();
Dictionary<string, Func<object, object>> getters = new Dictionary<string, Func<object, object>>();
Dictionary<string, Type> types = new Dictionary<string, Type>();
public JSONObjectMapping(Type type)
:base(type)
{
foreach (FieldInfo fieldInfo in type.GetFields(BindingFlags.Instance | BindingFlags.Public))
{
setters.Add(fieldInfo.Name, (object arg1, object arg2) => fieldInfo.SetValue(arg1, arg2));
getters.Add(fieldInfo.Name, (object arg) => fieldInfo.GetValue(arg));
types.Add(fieldInfo.Name, fieldInfo.FieldType);
}
foreach (PropertyInfo propertyInfo in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
setters.Add(propertyInfo.Name, (object arg1, object arg2) => propertyInfo.SetValue(arg1, arg2));
getters.Add(propertyInfo.Name, (object arg) => propertyInfo.GetValue(arg));
types.Add(propertyInfo.Name, propertyInfo.PropertyType);
}
}
public override object FromJson(JSONMapper mapper, JSONValue json)
{
JSONObject jObject = (JSONObject)json;
object o = Activator.CreateInstance(TargetType);
foreach (string name in setters.Keys)
{
if (jObject.ContainsKey(name))
setters[name](o, mapper.FromJson(jObject[name], types[name]));
}
return o;
}
public override JSONValue ToJson(JSONMapper mapper, object value)
{
JSONObject json = new JSONObject();
foreach (string name in getters.Keys)
{
json[name] = mapper.ToJson(getters[name](value));
}
return json;
}
}
}