Add more supported Types to JSONMapper

master
Harald Wolff 2020-02-24 17:39:46 +01:00
parent 93bad5af43
commit 2e6e0094ac
2 changed files with 30 additions and 1 deletions

View File

@ -9,6 +9,7 @@
// **/
using System;
using System.Collections.Generic;
using System.Collections;
namespace ln.json.mapping
{
public class JSONEnumerableMapping<T> : JSONMapping
@ -16,7 +17,7 @@ namespace ln.json.mapping
Type elementType;
public JSONEnumerableMapping()
:base(typeof(T))
: base(typeof(T))
{
elementType = typeof(T).GetGenericArguments()[0];
}
@ -30,6 +31,28 @@ namespace ln.json.mapping
IEnumerable<T> ie = (IEnumerable<T>)value;
JSONArray jsonArray = new JSONArray();
foreach (object element in ie)
jsonArray.Add(mapper.ToJson(element));
return jsonArray;
}
}
public class JSONEnumerableMapping : JSONMapping
{
public JSONEnumerableMapping()
: base(typeof(IEnumerable))
{
}
public override object FromJson(JSONMapper mapper, JSONValue json)
{
throw new NotSupportedException("IEnumerable can not be set from JSON");
}
public override JSONValue ToJson(JSONMapper mapper, object value)
{
IEnumerable ie = (IEnumerable)value;
JSONArray jsonArray = new JSONArray();
foreach (object element in ie)
jsonArray.Add(mapper.ToJson(element));

View File

@ -92,6 +92,8 @@ namespace ln.json.mapping
* Others
**/
Add(new JSONEnumerableMapping());
Add(new JSONMapping(
typeof(bool),
(JSONMapper arg1, object arg2) => ((bool)arg2) ? (JSONValue)JSONTrue.Instance : (JSONValue)JSONFalse.Instance,
@ -156,6 +158,10 @@ namespace ln.json.mapping
Add((JSONMapping)Activator.CreateInstance(typeof(JSONDictionaryMapping<,>).MakeGenericType(targetType.GetGenericArguments())));
}
}
else if (targetType.IsSubclassOf(typeof(IEnumerable)))
{
return mappings[typeof(IEnumerable)];
}
else
{
Add(new JSONObjectMapping(targetType));