.NET 7在反序列化请求时将对象转换为正确类型

huangapple go评论90阅读模式
英文:

.net 7 convert object to correct type when deserialising request

问题

在.NET 7 Web应用程序中,在控制器中反序列化数据时,可以将对象值转换为正确的类型吗?在数据库中,我有一个带有sql_variant的表,所以DTO具有对象属性:

public object Value {get; set;}

当我将JSON发送到控制器(参数是[FromBody]),我在Value中有:Value的类型为字符串:“text”,因此在使用EF Core保存之前,我需要将Value转换为字符串,因为如果不这样做,将出现错误:“从对象类型System.Text.Json.JsonElement到已知的托管提供程序本机类型不存在映射。”

英文:

It is possible to convert object value to correct type in .net 7 web application when data is deserializing in controller? In DB I have table with sql_variant, so DTO have object property:

public object Value {get; set;}

When I send json to controller (argument is [FromBody]), I have in value: Value kind = string: "text", so before saving with EF Core I need convert value to string, because if I don't do this I have error like: "No mapping exists from object type System.Text.Json.JsonElement to a known managed provider native type."

答案1

得分: 1

假设您必须使用 sql_variant 并且对于您的 Value 使用了 object 类型,那么您可能需要一个自定义JsonConverter

装饰您的 Dto 属性:

[JsonConverter(typeof(MyValueJsonConverter))]
public object Value { get; set; }

并且重写 JsonConverter

public class MyValueJsonConverter : JsonConverter<string>
{
    public override string Read(
        ref Utf8JsonReader reader,
        Type typeToConvert,
        JsonSerializerOptions options) =>
            reader.GetString()!;

    public override void Write(
        Utf8JsonWriter writer,
        string stringValue,
        JsonSerializerOptions options) =>
            writer.WriteStringValue(stringValue);
}
英文:

Assuming you must use sql_variant and are stuck with an object type for your Value, a custom JsonConverter is what you might need:

Decorate your Dto's property:

[JsonConverter(typeof(MyValueJsonConverter))]
public object Value {get; set;}

And override JsonConverter:

public class MyValueJsonConverter : JsonConverter&lt;string&gt;
{
    public override string Read(
        ref Utf8JsonReader reader,
        Type typeToConvert,
        JsonSerializerOptions options) =&gt;
            reader.GetString()!;

    public override void Write(
        Utf8JsonWriter writer,
        string stringValue,
        JsonSerializerOptions options) =&gt;
            writer.WriteStringValue(stringValue);
}

huangapple
  • 本文由 发表于 2023年7月10日 20:43:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76653863.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定