如果存在空字符串,Json.Net将in /floats中的空字符串转换为0。我在输入中使用数字类型,但空字段将是表单post调用中的空字符串。是否有将空字符串转换为空字符串的配置,或者像Json.net那样的0?
发布于 2021-12-13 15:00:57
只要使值为空即可
public class Model
{
[JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)]
public int? Value { get; set; }
}
结果将是
{ value: null }
你将无法在现实生活中创造出你的小提琴手json
string json = "{\"Value\":\"\"}";
但是,如果这是您的scholl项目,则可以使用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,那么您将拥有change 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}
发布于 2022-07-14 15:44:42
添加一个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);
https://stackoverflow.com/questions/70336610
复制相似问题