![](/img/trans.png)
[英]The null value cannot be assigned to a member with type System.Int64 which is a non-nullable value type
[英]Error converting value "null" to type 'System.Nullable`1[System.Int64]'
我有一個包含null
作為字符串的 JSON 對象,這是無法避免的,當我將此對象發送到我的 API 時,我收到此錯誤消息
將值“null”轉換為類型“System.Nullable`1[System.Int64]”時出錯
我的示例 JSON
{
Name:'Test',
Id:'null'
}
我的模型/DTO
class Class1{
public string Name {get;set;}
public long? Id {get;set;}
}
您可以通過使用JsonConverter
來處理將string
解析為long?
的邏輯來實現這一點long?
可以為空。
使用 Newtonsoft.Json 的第一個示例
public class NewtonsoftStringToLongJsonConverter : Newtonsoft.Json.JsonConverter
{
public override bool CanConvert(Type objectType)
{
throw new NotImplementedException();
}
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
{
var value = (string)reader.Value;
if (string.Equals("null", value, StringComparison.InvariantCultureIgnoreCase))
{
return null;
}
if (!long.TryParse(value, out var parsedValue))
{
return null;
}
return parsedValue;
}
public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
您的模型更新為
public class Class1
{
public string Name { get; set; }
[Newtonsoft.Json.JsonConverter(typeof(NewtonsoftStringToLongJsonConverter))]
public long? Id { get; set; }
}
第二個選項使用 System.Text.Json 實現。
public class SystemTextStringToLongJsonConverter : System.Text.Json.Serialization.JsonConverter<long?>
{
public override bool CanConvert(Type typeToConvert)
=> typeToConvert == typeof(long?);
public override long? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var value = reader.GetString();
if(string.Equals("null", value, StringComparison.InvariantCultureIgnoreCase))
{
return null;
}
if(!long.TryParse(value, out var parsedValue))
{
return null;
}
return parsedValue;
}
public override void Write(Utf8JsonWriter writer, long? value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
}
最后,您的模型更新為
public class Class1
{
public string Name { get; set; }
[Newtonsoft.Json.JsonConverter(typeof(NewtonsoftStringToLongJsonConverter))]
public long? Id { get; set; }
}
獲取json字符串。 做string.Replace("'null'", "null")
然后將它映射到你的dto
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.