Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

changes EmptyArrayOrDictionaryConverter to be backwards compatible with existing header behavior #125

Merged
merged 1 commit into from
Aug 11, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
}

}