最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Deserializing JSON text to an object in C# - Stack Overflow

programmeradmin3浏览0评论

I have the following class:

public class DeviceInfo
{
    public string? ip { get; set; }
    public string? deviceKey { get; set; }
    public long time { get; set; }
    public string? version { get; set; }
    public int faceCount { get; set; }
    public int personCount { get; set; }
}

On the other hand, I have this json string:

{
   "ip": "192.168.0.146",
   "deviceKey": "A34CC830D348437A",
   "time": "1741375392869",
   "version": "1.41.9.7",
   "faceCount": "0",
   "personCount": "0"
}

When executing:

JsonSerializerOptions? options = customImplementation ? new JsonSerializerOptions
{
    TypeInfoResolver = new DefaultJsonTypeInfoResolver
    {
        Modifiers = { JsonImplementationAttribute.ReadAttributeFromTypeInfo }
    }
} : null;
JsonSerializer.Deserialize<DeviceInfo>(json, options);

I got this error:

Exception: System.Text.Json.JsonException: The JSON value could not be converted to System.Int64. Path: $.time | LineNumber: 0 | BytePositionInLine: 75. ---> System.InvalidOperationException: Cannot get the value of a token type 'String' as a number. at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_ExpectedNumber(JsonTokenType tokenType) at System.Text.Json.Utf8JsonReader.TryGetInt64(Int64& value) at System.Text.Json.Utf8JsonReader.GetInt64() at System.Text.Json.Serialization.Metadata.JsonPropertyInfo1.ReadJsonAndSetMember(Object obj, ReadStack& state, Utf8JsonReader& reader) at System.Text.Json.Serialization.Converters.ObjectDefaultConverter1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value) at System.Text.Json.Serialization.JsonConverter1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value, Boolean& isPopulatedValue) at System.Text.Json.Serialization.JsonConverter1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state) --- End of inner exception stack trace --- at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& state, Utf8JsonReader& reader, Exception ex) at System.Text.Json.Serialization.JsonConverter1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state) at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan1 utf8Json, JsonTypeInfo1 jsonTypeInfo, Nullable1 actualByteCount)
at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan1 json, JsonTypeInfo1 jsonTypeInfo) at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options) at Modules.Integration.Extensions.JsonExtensions.ToObject[T](Object o, Boolean customImplementation) in C:\WorkingFolder\Projects\Desytec\Development\Desytec-Security-Platform\Web\Modules\Modules.Integration\Extensions\JsonExtensions.cs:line 29 at AdmsServer.Services.PassDeviceService.SaveOptions(String serialNumber) in C:\WorkingFolder\Projects\Desytec\Development\Desytec-Security-Platform\Web\Devices\AdmsServer\Services\PassDeviceService.cs:line 237 at AdmsServer.Controllers.Drivers.API.PassController.Heartbeat(DeviceInfo device) in C:\WorkingFolder\Projects\Desytec\Development\Desytec-Security-Platform\Web\Devices\AdmsServer\Controllers\Drivers\API\PassController.cs:line 83

What wrong thing do you see here?

Regards

I have the following class:

public class DeviceInfo
{
    public string? ip { get; set; }
    public string? deviceKey { get; set; }
    public long time { get; set; }
    public string? version { get; set; }
    public int faceCount { get; set; }
    public int personCount { get; set; }
}

On the other hand, I have this json string:

{
   "ip": "192.168.0.146",
   "deviceKey": "A34CC830D348437A",
   "time": "1741375392869",
   "version": "1.41.9.7",
   "faceCount": "0",
   "personCount": "0"
}

When executing:

JsonSerializerOptions? options = customImplementation ? new JsonSerializerOptions
{
    TypeInfoResolver = new DefaultJsonTypeInfoResolver
    {
        Modifiers = { JsonImplementationAttribute.ReadAttributeFromTypeInfo }
    }
} : null;
JsonSerializer.Deserialize<DeviceInfo>(json, options);

I got this error:

Exception: System.Text.Json.JsonException: The JSON value could not be converted to System.Int64. Path: $.time | LineNumber: 0 | BytePositionInLine: 75. ---> System.InvalidOperationException: Cannot get the value of a token type 'String' as a number. at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_ExpectedNumber(JsonTokenType tokenType) at System.Text.Json.Utf8JsonReader.TryGetInt64(Int64& value) at System.Text.Json.Utf8JsonReader.GetInt64() at System.Text.Json.Serialization.Metadata.JsonPropertyInfo1.ReadJsonAndSetMember(Object obj, ReadStack& state, Utf8JsonReader& reader) at System.Text.Json.Serialization.Converters.ObjectDefaultConverter1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value) at System.Text.Json.Serialization.JsonConverter1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value, Boolean& isPopulatedValue) at System.Text.Json.Serialization.JsonConverter1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state) --- End of inner exception stack trace --- at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& state, Utf8JsonReader& reader, Exception ex) at System.Text.Json.Serialization.JsonConverter1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state) at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan1 utf8Json, JsonTypeInfo1 jsonTypeInfo, Nullable1 actualByteCount)
at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan1 json, JsonTypeInfo1 jsonTypeInfo) at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options) at Modules.Integration.Extensions.JsonExtensions.ToObject[T](Object o, Boolean customImplementation) in C:\WorkingFolder\Projects\Desytec\Development\Desytec-Security-Platform\Web\Modules\Modules.Integration\Extensions\JsonExtensions.cs:line 29 at AdmsServer.Services.PassDeviceService.SaveOptions(String serialNumber) in C:\WorkingFolder\Projects\Desytec\Development\Desytec-Security-Platform\Web\Devices\AdmsServer\Services\PassDeviceService.cs:line 237 at AdmsServer.Controllers.Drivers.API.PassController.Heartbeat(DeviceInfo device) in C:\WorkingFolder\Projects\Desytec\Development\Desytec-Security-Platform\Web\Devices\AdmsServer\Controllers\Drivers\API\PassController.cs:line 83

What wrong thing do you see here?

Regards

Share edited Mar 7 at 19:57 dbc 118k26 gold badges264 silver badges387 bronze badges asked Mar 7 at 19:38 jstuardojstuardo 4,30614 gold badges83 silver badges173 bronze badges 4
  • time is declared as a longin the class, but it's a string in the json. faceCount and personCount will likely fail for the same reason. – Alejandro Commented Mar 7 at 19:43
  • It is a json string transmitted over Internet so obviously all members are string. How can this be faced then? – jstuardo Commented Mar 7 at 19:53
  • JSON supports both strings and numbers (and a few other types), regardless of how it's transmited. Since the value is enclosed in quotes, it means it's a string (a number won't have them). – Alejandro Commented Mar 7 at 19:59
  • The answer solved the problem. Thanks anyway. – jstuardo Commented Mar 7 at 20:03
Add a comment  | 

1 Answer 1

Reset to default 2

You can utilize the built in JsonSerializerOptions and set the NumberHandling Property, as its not set to read strings as numbers by default, you can change that like so:

public class Test
{
    public long time {get; set;}    
}
var o = new System.Text.Json.JsonSerializerOptions();
o.NumberHandling = System.Text.Json.Serialization
                .JsonNumberHandling.AllowReadingFromString;
        
string json = "{\"time\": \"99999000\"}";
var test = System.Text.Json.JsonSerializer.Deserialize<Test>(json, o);
Console.WriteLine(test.time);

Here's a link to a DotNet Fiddle: DotNetFiddle

发布评论

评论列表(0)

  1. 暂无评论