Skip to content

Commit b702a97

Browse files
committed
Fix JsonException when API returns count as string
The IPData API returns the `count` field as a JSON string, but the model expected System.Int32. Add IntJsonConverter to handle both string and number JSON tokens for the Count property. https://claude.ai/code/session_01V2uek6e28i6ARom7qVt1Mz
1 parent 10eb511 commit b702a97

2 files changed

Lines changed: 32 additions & 0 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
using System;
2+
using System.Text.Json;
3+
using System.Text.Json.Serialization;
4+
5+
namespace IPData.Http.Serializer
6+
{
7+
internal class IntJsonConverter : JsonConverter<int>
8+
{
9+
public override int Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
10+
{
11+
if (reader.TokenType == JsonTokenType.String)
12+
{
13+
var stringValue = reader.GetString();
14+
if (int.TryParse(stringValue, out var value))
15+
{
16+
return value;
17+
}
18+
19+
throw new JsonException($"Unable to convert \"{stringValue}\" to System.Int32.");
20+
}
21+
22+
return reader.GetInt32();
23+
}
24+
25+
public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options)
26+
{
27+
writer.WriteNumberValue(value);
28+
}
29+
}
30+
}

src/IPData/Models/IPLookupResult.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using System.Linq.Expressions;
55
using System.Text.Json.Serialization;
66
using IPData.Helpers.Extensions;
7+
using IPData.Http.Serializer;
78

89
namespace IPData.Models
910
{
@@ -88,6 +89,7 @@ public class IPLookupResult
8889
public int? Status { get; set; }
8990

9091
[JsonPropertyName("count")]
92+
[JsonConverter(typeof(IntJsonConverter))]
9193
public int Count { get; set; }
9294

9395
internal static string FieldName(Expression<Func<IPLookupResult, object>> expression)

0 commit comments

Comments
 (0)