106 lines
3.3 KiB
C#
106 lines
3.3 KiB
C#
// /**
|
|
// * File: Convert.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 ln.types.json.converter;
|
|
using Newtonsoft.Json.Linq;
|
|
namespace ln.types.json
|
|
{
|
|
public class JSONConvert
|
|
{
|
|
public JSONConvert Fallback { get; private set; }
|
|
|
|
List<IJsonConvert> converters = new List<IJsonConvert>();
|
|
|
|
public JSONConvert()
|
|
{
|
|
Fallback = DefaultInstance;
|
|
if (Fallback == null)
|
|
{
|
|
converters.Add(new JSONStringConverter());
|
|
converters.Add(new JSONNumberConverter());
|
|
converters.Add(new JSONDateTimeConverter());
|
|
converters.Add(new JSONTimeSpanConverter());
|
|
converters.Add(new JSONGuidConverter());
|
|
converters.Add(new JSONIPv4Converter());
|
|
converters.Add(new JSONNetwork4Converter());
|
|
}
|
|
}
|
|
public JSONConvert(IEnumerable<IJsonConvert> converters)
|
|
{
|
|
this.converters.AddRange(converters);
|
|
}
|
|
public JSONConvert(JSONConvert fallBack, IEnumerable<IJsonConvert> converters)
|
|
:this(converters)
|
|
{
|
|
Fallback = fallBack;
|
|
}
|
|
|
|
public string GetSkyType(Type targetType)
|
|
{
|
|
foreach (IJsonConvert convert in converters)
|
|
{
|
|
string skyType = convert.GetSkyType(targetType);
|
|
if (skyType != null)
|
|
return skyType;
|
|
}
|
|
if (Fallback != null)
|
|
return Fallback.GetSkyType(targetType);
|
|
return null;
|
|
}
|
|
|
|
public T JSON2Value<T>(JToken jToken)
|
|
{
|
|
object v = null;
|
|
if (JSON2Value(typeof(T),jToken,ref v))
|
|
{
|
|
if (v is T)
|
|
{
|
|
return (T)v;
|
|
}
|
|
}
|
|
throw new FormatException(String.Format("JSON2Value could not convert {0} to Type {1}",jToken.ToString(),typeof(T).FullName));
|
|
}
|
|
public bool JSON2Value(Type targetType, JToken jToken, ref object value)
|
|
{
|
|
foreach (IJsonConvert convert in converters)
|
|
{
|
|
if (convert.JSON2Value(targetType, jToken, ref value))
|
|
return true;
|
|
}
|
|
|
|
if (Fallback != null)
|
|
return Fallback.JSON2Value(targetType, jToken, ref value);
|
|
|
|
return false;
|
|
}
|
|
|
|
public bool Value2JSON(object value, ref JToken jToken)
|
|
{
|
|
foreach (IJsonConvert convert in converters)
|
|
{
|
|
if (convert.Value2JSON(value, ref jToken))
|
|
return true;
|
|
}
|
|
|
|
if (Fallback != null)
|
|
return Fallback.Value2JSON(value, ref jToken);
|
|
|
|
return false;
|
|
}
|
|
|
|
public static JSONConvert DefaultInstance { get; } = new JSONConvert();
|
|
|
|
public static bool ToValue(Type targetType, JToken jToken, ref object value) => DefaultInstance.JSON2Value(targetType, jToken, ref value);
|
|
public static bool ToJSON(object value, ref JToken jToken) => DefaultInstance.Value2JSON(value, ref jToken);
|
|
|
|
}
|
|
}
|