Skip to content

Commit

Permalink
Add GetRawValue() to return raw JSON in JsonSerializedField. (#9)
Browse files Browse the repository at this point in the history
<!-- Provide a general summary of your changes in the Title above -->
<!-- Apply the label "bug" or "enhacement" as applicable. -->

## Description
This pull request introduces an `GetRawValue()` method in the
`JsonSerializedField` class to directly return the raw JSON string. This
enhancement provides a more straightforward and efficient way to access
the underlying JSON without the need for additional deserialization.

## Motivation
The primary motivation for this change is to simplify the process of
working with JSON data, particularly in scenarios where the JSON is
deserialized, modified, and then re-serialized. In my case, I needed to
deserialize JSON into a `SitecoreLayoutResponseContent` object, apply
modifications, and then serialize it back to JSON. Previously, this
required a custom `JsonConverter` that accessed the `_json` field via
reflection. With this improvement, such workarounds are no longer
necessary, making the code cleaner and more maintainable.
  • Loading branch information
jbreuer authored Aug 29, 2024
1 parent 0ce00e4 commit a79266c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,15 @@ public class JsonSerializedField(JsonDocument doc)

private readonly string _json = doc != null ? doc.RootElement.GetRawText() : throw new ArgumentNullException(nameof(doc));

/// <summary>
/// Gets the raw JSON string representation of the field.
/// </summary>
/// <returns>A string containing the raw JSON data.</returns>
public string GetRawValue()
{
return _json;
}

/// <inheritdoc/>
protected override object? HandleRead(Type type)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,21 @@ public void TryRead_InvalidJson_ThrowsException()
field.Should().BeNull();
}

[Fact]
public void GetRawValue_ReturnsExpectedJson()
{
// Arrange
const string json = "{\"value\": 100}";
JsonDocument token = JsonDocument.Parse(json);
JsonSerializedField sut = new(token);

// Act
string result = sut.GetRawValue();

// Assert
result.Should().Be(json);
}

private class ValueField<T> : IField
{
public required T Value { get; set; }
Expand Down

0 comments on commit a79266c

Please sign in to comment.