forked from angularsen/UnitsNet
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
0e979a6
commit fae0272
Showing
2 changed files
with
28 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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; | ||
|
||
|
@@ -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> | ||
|
@@ -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; | ||
} | ||
} | ||
} |