Skip to content

Commit

Permalink
Added also JsonConverter for Unit
Browse files Browse the repository at this point in the history
  • Loading branch information
petrkoutnycz committed Aug 23, 2024
1 parent b963a63 commit 1ef7e49
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 0 deletions.
70 changes: 70 additions & 0 deletions src/FuncSharp.Tests/Product/UnitJsonConverterTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
using System.Text.Json;
using Xunit;

namespace FuncSharp.Tests;

public class UnitJsonConverterTests
{
private record DummyObjectWithUnit(string PropertyBefore, Unit Unit, string PropertyAfter);

[Fact]
public void Serializes_unit_only()
{
// Act
var json = JsonSerializer.Serialize(Unit.Value);

// Assert
Assert.Equal("{}", json);
}

[Fact]
public void Deserializes_unit_only()
{
// Act
var value = JsonSerializer.Deserialize<Unit>("{}");

// Assert
Assert.Equal(Unit.Value, value);
}

[Fact]
public void Serializes_complex_object_including_unit()
{
// Arrange
var value = new DummyObjectWithUnit("before", Unit.Value, "after");

// Act
var json = JsonSerializer.Serialize(value);

// Assert
Assert.Equal(@"{""PropertyBefore"":""before"",""Unit"":{},""PropertyAfter"":""after""}", json);
}

[Fact]
public void Deserializes_complex_object_including_unit()
{
// Arrange
var json = @"{""PropertyBefore"":""before"",""Unit"":{},""PropertyAfter"":""after""}";

// Act
var value = JsonSerializer.Deserialize<DummyObjectWithUnit>(json);

// Assert
Assert.Equal("before", value.PropertyBefore);
Assert.Equal(Unit.Value, value.Unit);
Assert.Equal("after", value.PropertyAfter);
}

[Fact]
public void Serializes_try_with_success_as_unit()
{
// Arrange
var value = Try.Success<Unit, string>(Unit.Value);

// Act
var json = JsonSerializer.Serialize(value);

// Assert
Assert.Equal(@"{""IsSuccess"":true,""Value"":{}}", json);
}
}
3 changes: 3 additions & 0 deletions src/FuncSharp/Product/Unit.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@

using System.Text.Json.Serialization;

namespace FuncSharp;

/// <summary>
/// The Unit type (product of zero types). It has only one instance.
/// </summary>
[JsonConverter(typeof(UnitJsonConverter))]
public sealed class Unit : Product0
{
private Unit()
Expand Down
20 changes: 20 additions & 0 deletions src/FuncSharp/Product/UnitJsonConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using System;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace FuncSharp;

public sealed class UnitJsonConverter : JsonConverter<Unit>
{
public override Unit Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
reader.Read();
return Unit.Value;
}

public override void Write(Utf8JsonWriter writer, Unit value, JsonSerializerOptions options)
{
writer.WriteStartObject();
writer.WriteEndObject();
}
}

0 comments on commit 1ef7e49

Please sign in to comment.