source: branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/Converters/BaseConverter.cs @ 17284

Last change on this file since 17284 was 17284, checked in by dpiringe, 3 years ago

#3026: renamed namespace and project from HeuristicLab.Manufacture to HeuristicLab.JsonInterface

File size: 1.3 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using System.Threading.Tasks;
6using HeuristicLab.Core;
7using Newtonsoft.Json.Linq;
8
9namespace HeuristicLab.JsonInterface {
10  public abstract class BaseConverter : IJsonItemConverter
11  {
12    public JsonItem Extract(IItem value) {
13      JsonItem data = ExtractData(value);
14      data.Name = String.IsNullOrEmpty(data.Name) ? value.ItemName : data.Name;
15      return data;
16    }
17
18    public void Inject(IItem item, JsonItem data) {
19      if(data.Reference != null) {
20        JsonItem.Merge(data, data.Reference);
21      }
22      InjectData(item, data);
23    }
24
25    public abstract void InjectData(IItem item, JsonItem data);
26    public abstract JsonItem ExtractData(IItem value);
27
28    #region Helper
29    protected ValueType CastValue<ValueType>(object obj) {
30      if (obj is JToken)
31        return (obj.Cast<JToken>()).ToObject<ValueType>();
32      else if (obj is IConvertible)
33        return Convert.ChangeType(obj, typeof(ValueType)).Cast<ValueType>();
34      else return (ValueType)obj;
35    }
36
37    protected IItem Instantiate(Type type, params object[] args) =>
38      (IItem)Activator.CreateInstance(type,args);
39
40    protected IItem Instantiate<T>(params object[] args) => Instantiate(typeof(T), args);
41    #endregion
42  }
43}
Note: See TracBrowser for help on using the repository browser.