Skip to content

Commit

Permalink
Handle decimals in JSON response (#1164)
Browse files Browse the repository at this point in the history
* Handle decimals in JSON response

e.g. decimal being returned for sw_version

* Add test case for parsing longs
  • Loading branch information
seancallinan authored Sep 1, 2024
1 parent e37bffb commit c9bc201
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,50 @@ public void TestConverModelIsArrayInvalidString()

hassDevice!.Model.Should().BeNull();
}

[Fact]
public void TestConverDecimalString()
{
var hassDevice = JsonSerializer.Deserialize<HassDevice>("""
{
"config_entries": [],
"connections": [],
"manufacturer": "Google Inc.",
"model": 123123,
"name": 123,
"serial_number": "1.0",
"sw_version": 12.3,
"hw_version": null,
"id": "42cdda32a2a3428e86c2e27699d79ead",
"via_device_id": null,
"area_id": null,
"name_by_user": null
}
""");

hassDevice!.SoftwareVersion.Should().Be("12.3");
}

[Fact]
public void TestConverLongString()
{
var hassDevice = JsonSerializer.Deserialize<HassDevice>("""
{
"config_entries": [],
"connections": [],
"manufacturer": "Google Inc.",
"model": 123123,
"name": 123,
"serial_number": "1.0",
"sw_version": 1234567890123,
"hw_version": null,
"id": "42cdda32a2a3428e86c2e27699d79ead",
"via_device_id": null,
"area_id": null,
"name_by_user": null
}
""");

hassDevice!.SoftwareVersion.Should().Be("1234567890123");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,14 @@ class EnsureStringConverter : JsonConverter<string?>
return reader.GetString();

case JsonTokenType.Number:
var stringValue = reader.GetInt32();
return stringValue.ToString(CultureInfo.InvariantCulture);
if (reader.TryGetInt32(out var intValue))
return intValue.ToString(CultureInfo.InvariantCulture);
if (reader.TryGetInt64(out var longValue))
return longValue.ToString(CultureInfo.InvariantCulture);
if (reader.TryGetDouble(out var doubleValue))
return doubleValue.ToString(CultureInfo.InvariantCulture);

return null;

default:
reader.Skip();
Expand Down

0 comments on commit c9bc201

Please sign in to comment.