Json.Net 如果存在空字符串,则将 ints/floats 中的空字符串转换为 0。我在输入中使用数字类型,但空字段在表单调用后将是空字符串。是否有像 Json.net 那样将空字符串转换为 Null 或 0 的配置?
添加 JsonConverter:这是我用来转换 int 的示例。如果读取的值是除 int 以外的任何值,则返回 0。
public class JsonInt32Converter : JsonConverter<int>
{
public override bool CanConvert(Type typeToConvert)
{
return typeToConvert == typeof(int);
}
public override int Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
try
{
var value = reader.GetInt32();
return value;
}
catch
{
return 0;
}
}
public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
}
注意:我不需要为我的程序进行写入,所以我没有实现它。
然后将其添加到您的序列化器选项中:
var options = new JsonSerializerOptions();
options.Converters.Add(new JsonInt32Converter());
var myObject = JsonSerializer.Deserialize<MyObject>(jsonstring, options);
只需将值设为可为空即可
public class Model
{
[JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)]
public int? Value { get; set; }
}
结果将会是
{ value: null }
你将无法在现实生活中创建你的 fiddler json
string json = "{\"Value\":\"\"}";
但如果是学校项目,你可以使用Newtonsoft.Json反序列化它(安装nuget包)
Model d = JsonConvert.DeserializeObject<Model>(json);
Console.WriteLine("Value: " + d.Value);
string s =JsonConvert.SerializeObject(d);
Console.WriteLine("json: " + s);
}
输出
Value:
json: {"Value":null}
但是如果您仍然想使用 Text.Json 那么您将需要更改 Model 类
public class Model
{
private string _val;
[JsonPropertyName("Value")]
public string Val {
get { return string.IsNullOrEmpty(_val) ? null : _val; }
set { _val = value;}
}
[System.Text.Json.Serialization.JsonIgnore]
public int Value
{
get { return string.IsNullOrEmpty(Val) ? 0 : Convert.ToInt32(Val); }
set { Val = value==0? null: value.ToString(); }
}
}
输出
Value: 0
json: {"Value":null}