-
Notifications
You must be signed in to change notification settings - Fork 46
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This commit introduces a new dependency on System.Text.Json. It also adds new code to convert NodaMoney objects to and from JSON. This includes modifications to the NodaMoney.csproj file and the creation of MoneyJsonConverter.cs, which contains the converter implementation.
- Loading branch information
1 parent
49c3ad7
commit 045e475
Showing
3 changed files
with
115 additions
and
0 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
using System.Text.Json; | ||
using System.Text.Json.Serialization; | ||
|
||
namespace NodaMoney; | ||
|
||
public class MoneyJsonConverter : JsonConverter<Money> | ||
{ | ||
public override Money Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | ||
{ | ||
if (reader.TokenType != JsonTokenType.StartObject) | ||
{ | ||
throw new JsonException(); | ||
} | ||
|
||
decimal amount = 0; | ||
string currencyCode = null; | ||
|
||
while (reader.Read()) | ||
{ | ||
if (reader.TokenType == JsonTokenType.EndObject) | ||
{ | ||
return new Money(amount, Currency.FromCode(currencyCode)); | ||
} | ||
|
||
if (reader.TokenType == JsonTokenType.PropertyName) | ||
{ | ||
string propertyName = reader.GetString(); | ||
reader.Read(); | ||
switch (propertyName) | ||
{ | ||
case "Amount": | ||
amount = reader.GetDecimal(); | ||
break; | ||
case "Currency": | ||
currencyCode = reader.GetString(); | ||
break; | ||
} | ||
} | ||
} | ||
|
||
throw new JsonException(); | ||
} | ||
|
||
public override void Write(Utf8JsonWriter writer, Money value, JsonSerializerOptions options) | ||
{ | ||
writer.WriteStartObject(); | ||
writer.WriteNumber("Amount", value.Amount); | ||
writer.WriteString("Currency", value.Currency.Code); | ||
writer.WriteEndObject(); | ||
} | ||
} |
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