Add support for JSONExceptionMapping

master
Harald Wolff 2019-10-04 19:40:39 +02:00
parent 1a24ea939e
commit 28446ab628
3 changed files with 35 additions and 1 deletions

View File

@ -54,6 +54,7 @@
<Compile Include="attributes\JSONMappingAttribute.cs" />
<Compile Include="mapping\JSONEnumMapping.cs" />
<Compile Include="mapping\JSONDictionaryMapping.cs" />
<Compile Include="mapping\JSONExceptionMapping.cs" />
</ItemGroup>
<ItemGroup>
<Folder Include="mapping\" />

View File

@ -0,0 +1,28 @@
using System;
namespace ln.json.mapping
{
public class JSONExceptionMapping : JSONMapping
{
public JSONExceptionMapping()
: base(typeof(Exception))
{
}
public JSONExceptionMapping(Type exceptionType)
: base(exceptionType)
{
}
public override JSONValue ToJson(JSONMapper mapper, object value)
{
JSONObject jObject = new JSONObject();
Exception e = value as Exception;
jObject["ExceptionType"] = mapper.ToJson(value.GetType().Name);
jObject["Message"] = mapper.ToJson(e.Message);
jObject["InnerException"] = mapper.ToJson(e.InnerException);
return jObject;
}
}
}

View File

@ -132,13 +132,18 @@ namespace ln.json.mapping
{
Add(new JSONEnumMapping(targetType));
}
else if (targetType.IsSubclassOf(typeof(Exception)))
{
Add(new JSONExceptionMapping(targetType));
}
else if (targetType.IsGenericType)
{
Type genericTypeDefinition = targetType.GetGenericTypeDefinition();
if (genericTypeDefinition.Equals(typeof(IEnumerable<>)))
{
Add((JSONMapping)Activator.CreateInstance(typeof(JSONEnumerableMapping<>).MakeGenericType(targetType.GetGenericArguments()[0])));
} else if (genericTypeDefinition.Equals(typeof(Dictionary<,>)))
}
else if (genericTypeDefinition.Equals(typeof(Dictionary<,>)))
{
Add((JSONMapping)Activator.CreateInstance(typeof(JSONDictionaryMapping<,>).MakeGenericType(targetType.GetGenericArguments())));
}