在.NET中很难找到工作者和I/O线程的详细但简单的描述
我对这个主题有什么了解(但可能在技术上不精确):
不清楚的是:
我尝试从 Newtonsoft.Json 迁移到 System.Text.Json。我想反序列化抽象类。Newtonsoft.Json 为此具有 TypeNameHandling。有没有办法通过.net core 3.0 上的 System.Text.Json 反序列化抽象类?
使用 .Net Core 3 的新 System.Text.Json JsonSerializer,如何自动转换类型(例如 int 到 string 和 string 到 int)?例如,这会引发异常,因为id在 JSON 中是数字,而在 C# 中需要Product.Id一个字符串:
public class HomeController : Controller
{
public IActionResult Index()
{
var json = @"{""id"":1,""name"":""Foo""}";
var o = JsonSerializer.Deserialize<Product>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
});
return View();
}
}
public class Product
{
public string Id { get; set; }
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
Newtonsoft 的 Json.Net 很好地处理了这个问题。如果您在 C# 期望字符串时传入数值并不重要(反之亦然),一切都按预期反序列化。如果您无法控制作为 JSON 传入的类型格式,您如何使用 System.Text.Json 处理此问题?
我将.Net Core的版本从预览2升级到了预览6,这打破了两件事。最重要的是,我不能再使用newtonsoft JSON。
ConfigureServices中的AddNewtonsoftJson似乎什么也不做,新的Json序列化器似乎仅对属性起作用,而对字段不起作用。它没有看到JSONIgnoreAttribute。
在ConfigureServices中(在Startup中),我有一行
services.AddMvc(x => x.EnableEndpointRouting = false).AddNewtonsoftJson();
似乎没有做应做的事情。在我的应用程序中,仅属性被序列化,而不是字段,并且[JSONIgnore]属性不执行任何操作。
我可以通过推广所有需要成为属性的公共领域来解决缺少的领域,但是我必须能够忽略一些领域。
还有其他人吗?如何获得新的JSON序列化程序以忽略某些属性并序列化公共字段,或者返回Newtonsoft?
我有带有科学记数法数字的 JSON,例如1.83E+2。使用 Json.NET 将其反序列化为 along对我来说效果很好,但是当我用 System.Text.Json 中的新反序列化器替换反序列化器时,它会抛出一个JsonException:
System.Text.Json.JsonException:“无法将 JSON 值转换为 System.Int64。...'
这是一个可重现的示例:
static void Main()
{
// test1 is 183
var test1 = Newtonsoft.Json.JsonConvert.DeserializeObject<Foo>(@"{""Bar"": 1.83E+2}");
// throws JsonException
var test2 = System.Text.Json.JsonSerializer.Deserialize<Foo>(@"{""Bar"": 1.83E+2}");
}
public class Foo
{
public long Bar { get; set; }
}
Run Code Online (Sandbox Code Playgroud)