英文:
.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<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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论