首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >System.text.json将空字符串转换为int

System.text.json将空字符串转换为int
EN

Stack Overflow用户
提问于 2021-12-13 14:55:46
回答 2查看 784关注 0票数 1

如果存在空字符串,Json.Net将in /floats中的空字符串转换为0。我在输入中使用数字类型,但空字段将是表单post调用中的空字符串。是否有将空字符串转换为空字符串的配置,或者像Json.net那样的0?

在下面小提琴。https://dotnetfiddle.net/CDNicW

EN

回答 2

Stack Overflow用户

发布于 2021-12-13 15:00:57

只要使值为空即可

代码语言:javascript
运行
复制
public class Model
    {
         [JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)]
        public int? Value { get; set; }
    }

结果将是

代码语言:javascript
运行
复制
{ value: null }

你将无法在现实生活中创造出你的小提琴手json

代码语言:javascript
运行
复制
string json = "{\"Value\":\"\"}";

但是,如果这是您的scholl项目,则可以使用Newtonsoft.Json (安装nuget包)对其进行反序列化。

代码语言:javascript
运行
复制
    Model d = JsonConvert.DeserializeObject<Model>(json);
    Console.WriteLine("Value: " + d.Value);
    string s =JsonConvert.SerializeObject(d);
    Console.WriteLine("json: " + s);
}

输出

代码语言:javascript
运行
复制
Value: 
json: {"Value":null}

但是,如果您仍然希望使用Text.Json,那么您将拥有change Model类

代码语言:javascript
运行
复制
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(); }
    }
}

输出

代码语言:javascript
运行
复制
Value: 0
json: {"Value":null}
票数 0
EN

Stack Overflow用户

发布于 2022-07-14 15:44:42

添加一个JsonConverter:下面是我用来转换int的一个例子。如果所读取的值是除int以外的任何内容,则返回0。

代码语言:javascript
运行
复制
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();
    }
}

注意:我不必为我的程序写东西,所以我没有实现它。

然后将其添加到序列化程序选项中:

代码语言:javascript
运行
复制
var options = new JsonSerializerOptions();
options.Converters.Add(new JsonInt32Converter());
var myObject = JsonSerializer.Deserialize<MyObject>(jsonstring, options);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70336610

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档