Skip to content

Remove Dual JSON Serialization in SaveAndReturnMessageItem #1124

Description

@samsmithnz

Problem

SaveAndReturnMessageItem() uses both System.Text.Json (for serialization) and Newtonsoft.Json (for deserialization), causing:

  • Double deserialization overhead
  • Inconsistent behavior between libraries
  • Unnecessary dependency on Newtonsoft.Json
  • Performance degradation

Current Implementation

Location: SamSmithNZ.Web/Services/BaseServiceApiClient.cs (Lines 83-99)

string jsonInString = JsonSerializer.Serialize(obj); // System.Text.Json
// ...
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(responseString); // Newtonsoft
result = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(jsonObj?.ToString()); // Double deserialize!

Proposed Solution

string jsonInString = JsonSerializer.Serialize(obj);
StringContent content = new(jsonInString, Encoding.UTF8, "application/json");
HttpResponseMessage response = await _client.PostAsync(url, content);

if (response.IsSuccessStatusCode)
{
    await using Stream stream = await response.Content.ReadAsStreamAsync();
    return await JsonSerializer.DeserializeAsync<T>(stream);
}
return default;

Benefits

  • ✅ 50%+ faster deserialization
  • ✅ Lower memory allocation
  • ✅ Consistent JSON library usage
  • ✅ Removes dynamic type usage

Acceptance Criteria

  • Method uses only System.Text.Json
  • No breaking changes to API contracts
  • All integration tests pass
  • Performance benchmark shows improvement

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions