当前位置: 首页 > 工具软件 > JSONVALUE > 使用案例 >

【System.Text.Json】The JSON value could not be converted to System.Int32.

邬良才
2023-12-01

System.Text.Json不会自动把json中的字符串转换为int类型,需要添加NumberHandling配置。

public class ClassWithInts
{
    public int NumberOne { get; set; }
    public int NumberTwo { get; set; }
}

var options = new JsonSerializerOptions
{
    NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.WriteAsString 
};

string json = @"{""Number1"":1,""Number2"":""2""}";

ClassWithInts @class = JsonSerializer.Deserializer<ClassWithInts>(json, options);
Console.WriteLine(@class.NumberOne); // 1
Console.WriteLine(@class.NumberTwo); // 2

json = JsonSerializer.Serialize(@class, options);
Console.WriteLine(json); // @"{""Number1"":""1"",""Number2"":""2""}";
 类似资料:

相关阅读

相关文章

相关问答