You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core API反序列化FromBody参数时如何自动将数字转为字符串

实现方案

.NET 5默认使用System.Text.Json作为序列化组件,你可以通过自定义JsonConverter实现非字符串类型自动转字符串的需求,如果你项目已切换到Newtonsoft.Json也可参考对应方案:


方案1:基于System.Text.Json(默认序列化组件)

步骤1:自定义字符串转换转换器

using System;
using System.Text.Json;
using System.Text.Json.Serialization;

public class AutoToStringConverter : JsonConverter<string>
{
    public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        return reader.TokenType switch
        {
            JsonTokenType.Number => reader.GetRawText(),
            JsonTokenType.True => bool.TrueString,
            JsonTokenType.False => bool.FalseString,
            JsonTokenType.String => reader.GetString(),
            JsonTokenType.Null => null,
            _ => reader.GetRawText()
        };
    }

    public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value);
    }
}

步骤2:注册转换器

两种注册方式按需选择:

  • 全局生效(所有string类型属性都支持自动转)
    在Startup.cs的ConfigureServices方法中添加配置:
services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.Converters.Add(new AutoToStringConverter());
    });
  • 仅指定属性生效
    在对应模型属性上加特性即可:
public class Product
{
    [JsonConverter(typeof(AutoToStringConverter))]
    public string ProductNo { get; set; }
    public string ProductName { get; set; }
}

方案2:基于Newtonsoft.Json

如果你的项目已经切换到Newtonsoft.Json序列化,用以下方案实现:

步骤1:自定义转换器

using Newtonsoft.Json;
using System;

public class AutoToStringConverter : JsonConverter<string>
{
    public override string ReadJson(JsonReader reader, Type objectType, string existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        return reader.Value?.ToString();
    }

    public override void WriteJson(JsonWriter writer, string value, JsonSerializer serializer)
    {
        writer.WriteValue(value);
    }
}

步骤2:注册转换器

  • 全局生效:
services.AddControllers()
    .AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.Converters.Add(new AutoToStringConverter());
    });
  • 仅指定属性生效:
public class Product
{
    [JsonConverter(typeof(AutoToStringConverter))]
    public string ProductNo { get; set; }
    public string ProductName { get; set; }
}

配置完成后,你示例中数字类型的productNo:123456会被自动转换为字符串"123456",不会抛出序列化异常。

内容的提问来源于stack exchange,提问作者qwer11121

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 18:45:05