The JSON value could not be converted to System.Int32

前端 未结 6 1851
南方客
南方客 2020-12-03 02:39

I want to send data of object to my Web API. The API accepts a parameter of class, which properties are type of int and string.

This is my class:

publi         


        
6条回答
  •  半阙折子戏
    2020-12-03 03:08

    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
        {
            public override int Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options)
            {
                if (reader.TokenType == JsonTokenType.String)
                {
                    ReadOnlySpan 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()));
    

提交回复
热议问题