Skip to content

Commit

Permalink
changes to be more backwards compat (#125)
Browse files Browse the repository at this point in the history
  • Loading branch information
feinoujc authored Aug 11, 2020
1 parent 38dfede commit 85daf6f
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 20 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using System;
using System.Collections.Generic;
using Mandrill.net.Serialization;
using Mandrill.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

Expand Down
32 changes: 13 additions & 19 deletions src/Mandrill.net/Serialization/EmptyArrayOrDictionaryConverter.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Mandrill.net.Serialization
namespace Mandrill.Serialization
{
/// <summary>
/// This converter will allow an empty array to be converted to a dictionary
/// This converter will allow an empty array to be converted to an empty dictionary
/// </summary>
internal class EmptyArrayOrDictionaryConverter : JsonConverter
{
Expand All @@ -20,28 +16,26 @@ public override bool CanConvert(Type objectType)

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken token = JToken.Load(reader);

if (token.Type == JTokenType.Object)
{
return token.ToObject(objectType);
}
else if (token.Type == JTokenType.Array)
if (reader.TokenType == JsonToken.StartArray)
{
if (!token.HasValues)
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
// Create empty dictionary
return Activator.CreateInstance(objectType);
// discard
}
return existingValue ?? serializer.ContractResolver.ResolveContract(objectType).DefaultCreator();
}

throw new JsonSerializationException("Object or empty array expected");
// default behavior
existingValue = existingValue ?? serializer.ContractResolver.ResolveContract(objectType).DefaultCreator();
serializer.Populate(reader, existingValue);
return existingValue;
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value);
throw new NotSupportedException("CanWrite is false");
}

public override bool CanWrite => false;
}

}

0 comments on commit 85daf6f

Please sign in to comment.