问题
i want to send data of object to my web api. the api accept a parameter of class,which properties are type of int and string.
this is my class:
public class deneme
{
public int ID { get; set; }
public int sayi { get; set; }
public int reqem { get; set; }
public string yazi { get; set; }
}
this is my json object:
{
"id":0,
"sayi":"9",
"reqem":8,
"yazi":"sss"
}
i want the api read the property "sayi" as integer. but because it cant, it gives the error: The JSON value could not be converted to System.Int32. Path: $.sayi
How could i solve this problem?
回答1:
For Asp.Net Core 3.0, it uses System.Text.Json for serialization and deserialization.
For using old behavior, you could use Json.NET in an ASP.NET Core 3.0 project by referencing Json.NET support.
Short Answer:
- Install
Microsoft.AspNetCore.Mvc.NewtonsoftJsonwhich is preview version. - Change to
services.AddControllers().AddNewtonsoftJson();
回答2:
First you should create a JsonConverter for it:
using System;
using System.Buffers;
using System.Buffers.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace sample_22_backend.Converters
{
public class IntToStringConverter : JsonConverter<int>
{
public override int Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.String)
{
ReadOnlySpan<byte> span = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan;
if (Utf8Parser.TryParse(span, out int number, out int bytesConsumed) && span.Length == bytesConsumed)
{
return number;
}
if (int.TryParse(reader.GetString(), out number))
{
return number;
}
}
return reader.GetInt32();
}
public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString());
}
}
}
Then use it this way on your model's properties:
[JsonConverter(typeof(IntToStringConverter))]
public int GenreId { set; get; }
Or you can add it globally:
services.AddControllers()
.AddJsonOptions(options =>
options.JsonSerializerOptions.Converters.Add(new IntToStringConverter()));
来源:https://stackoverflow.com/questions/57626878/the-json-value-could-not-be-converted-to-system-int32