Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
shaeussler committed Jul 21, 2023
1 parent 0e979a6 commit fae0272
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,15 @@ public void NullValue_ExpectNullReturned()
Assert.Null(deserializedNullMass);
}

[Fact]
public void EmptyJsonValue_ExpectNullReturned()
{
var json = "{}";
var deserializedNullMass = DeserializeObject<Mass?>(json);

Assert.Null(deserializedNullMass);
}

[Fact]
public void NullValueNestedInObject_ExpectValueDeserializedToNullCorrectly()
{
Expand Down
24 changes: 19 additions & 5 deletions UnitsNet.Serialization.JsonNet/UnitsNetIQuantityJsonConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Copyright 2013 Andreas Gullberg Larsen ([email protected]). Maintained at https://github.com/angularsen/UnitsNet.

using System;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

Expand Down Expand Up @@ -36,6 +37,8 @@ public override void WriteJson(JsonWriter writer, IQuantity? value, JsonSerializ
serializer.Serialize(writer, valueUnit);
}

private static bool IsEmptyJson(string source) => Regex.IsMatch(source, @"^\s*{\s*}\s*", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.CultureInvariant);

/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
Expand All @@ -51,24 +54,35 @@ public override void WriteJson(JsonWriter writer, IQuantity? value, JsonSerializ
public override IQuantity? ReadJson(JsonReader reader, Type objectType, IQuantity? existingValue, bool hasExistingValue,
JsonSerializer serializer)
{
var ret = existingValue;

reader = reader ?? throw new ArgumentNullException(nameof(reader));
serializer = serializer ?? throw new ArgumentNullException(nameof(serializer));

if (reader.TokenType == JsonToken.Null)
{
return existingValue;
return ret;
}

var token = JToken.Load(reader);

var valueUnit = ReadValueUnit(token);
var json = token.ToString();

if (valueUnit == null)
if (!string.IsNullOrWhiteSpace(json) && !IsEmptyJson(json))
{
return token.ToObject<IQuantity>(serializer);
var valueUnit = ReadValueUnit(token);

if (valueUnit == null)
{
ret = token.ToObject<IQuantity>(serializer);
}
else
{
ret = ConvertValueUnit(valueUnit);
}
}

return ConvertValueUnit(valueUnit);
return ret;
}
}
}

0 comments on commit fae0272

Please sign in to comment.