【问题标题】:System.text.json convert empty string to intSystem.text.json 将空字符串转换为 int
【发布时间】:2021-12-13 14:55:46
【问题描述】:

如果存在空字符串,Json.Net 会将 ints/floats 中的空字符串转换为 0。我在输入中使用数字类型,但空字段将是表单发布调用中的空字符串。是否有将空字符串转换为 Null 或 0 的配置,如 Json.net ?

在下面摆弄。 https://dotnetfiddle.net/CDNicW

【问题讨论】:

    标签: c# .net system.text.json


    【解决方案1】:

    让值可以为空

    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,那么您将需要更改 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}
    

    【讨论】:

    • 我做到了。它仍然是同样的错误,你试过我的小提琴吗?我需要它在空字符串上默认为 0 或 null。
    • @RedLotus 错误是什么?你从哪里得到你试图反序列化的json?是菊苣。请显示创建此 json 的代码
    • 我在问 System.Text.Json .. 我还说 Json.net(Newtonsoft) 可以处理这个问题。我在我的问题上发布了网址。我在问它将如何在 System.Text.Json 中完成,我知道它支持转换器我只是想知道它是否已经完成。
    • @RedLotus 如果您正在寻找问题,那么您应该选择 JavaScriptConverter。它比 text.json 有更多的错误
    • 我现在只坚持使用 Newtonsoft。似乎 System.text 需要相同类型的 JSON 并且不进行转换,因为 html 中的大多数表单默认为空字符串。同样对于日期字段上的空字符串,它也会引发错误。 Newtonsoft 将这些字段转换为默认值,如果可以为空,则将其设置为 null。
    猜你喜欢
    • 2011-03-01
    • 2011-10-02
    • 2011-03-06
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多