// /** // * 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; using ln.json.attributes; namespace ln.json.mapping { public interface IJSONApply { void Apply(JSONObject json); } public class JSONObjectMapping : JSONMapping { Dictionary> setters = new Dictionary>(); Dictionary> getters = new Dictionary>(); Dictionary types = new Dictionary(); public JSONObjectMapping(Type type) : base(type) { foreach (FieldInfo fieldInfo in type.GetFields(BindingFlags.Instance | BindingFlags.Public)) { JSONMappingAttribute mappingAttribute = fieldInfo.GetCustomAttribute(); if ((mappingAttribute == null) || !mappingAttribute.Private) { 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)) { JSONMappingAttribute mappingAttribute = propertyInfo.GetCustomAttribute(); if ((propertyInfo.GetIndexParameters().Length == 0) && ((mappingAttribute == null) || !mappingAttribute.Private)) { 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) { if (json is JSONObject) { JSONObject jObject = (JSONObject)json; object o = Activator.CreateInstance(TargetType); Apply(mapper, jObject, o); return o; } else { return json.ToNative(); } } 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; } public void Apply(JSONObject json, object o) => Apply(JSONMapper.DefaultMapper, json, o); public void Apply(JSONMapper mapper,JSONObject json,object o) { if (o is IJSONApply) { (o as IJSONApply).Apply(json); } else { foreach (string name in setters.Keys) { if (json.ContainsKey(name)) setters[name](o, mapper.FromJson(json[name], types[name])); } } } } }