gpt4 book ai didi

c# - 使用 newtonsoft json.net 反序列化字符串时,如何将空字符串转换为 null 以获得可为 null 的 int?

转载 作者:太空狗 更新时间:2023-10-29 22:08:23 28 4
gpt4 key购买 nike

例如,如果我有

public class MyClass
{
public Int32? Id { get;set; }
public string Description { get;set; }
}

我的 json 字符串如下所示:

"{\"Id\":\"\",\"Description\":\"test\"}"

我收到错误消息“无法将字符串转换为整数”

最佳答案

正如 svick 所说,您应该改为修复 Json。但是,如果它是您无法控制的外部 Json,那么您可以使用 JsonConverter。

public class StringToNIntConverter : JsonConverter
{

public override bool CanConvert(Type objectType)
{
return objectType == typeof(int?);
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
if (reader.TokenType == JsonToken.Integer)
return reader.Value;

if (reader.TokenType == JsonToken.String)
{
if (string.IsNullOrEmpty((string)reader.Value))
return null;
int num;
if (int.TryParse((string)reader.Value, out num))
return num;

throw new JsonReaderException(string.Format("Expected integer, got {0}", reader.Value));
}
throw new JsonReaderException(string.Format("Unexcepted token {0}", reader.TokenType));
}

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

public class MyClass
{
[JsonConverter(typeof(StringToNIntConverter))]
public Int32? Id { get; set; }
public string Description { get; set; }
}

关于c# - 使用 newtonsoft json.net 反序列化字符串时,如何将空字符串转换为 null 以获得可为 null 的 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9825624/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com