ASP.Net Core 中的 JSON 序列化/反序列化 [英] JSON serialization/deserialization in ASP.Net Core
问题描述
既然没有JavaScriptSerializer
,那么可以使用什么原生实现来处理这个问题?
Since there is no JavaScriptSerializer
, what native implementation can be used to handle this?
我注意到 JsonResult
并且我可以用它将数据格式化为 JSON,但是我如何反序列化?
I noticed JsonResult
and I can format data to JSON with this, but how do I deserialize?
或者我在 project.json
中遗漏了一些依赖?
Or maybe I am missing some dependencies in project.json
?
推荐答案
你可以使用 Newtonsoft.Json
,它是 Microsoft.AspNet.Mvc.ModelBinding
的一个依赖是 Microsoft.AspNet.Mvc
的依赖项.因此,您无需在 project.json 中添加依赖项.
You can use Newtonsoft.Json
, it's a dependency of Microsoft.AspNet.Mvc.ModelBinding
which is a dependency of Microsoft.AspNet.Mvc
. So, you don't need to add a dependency in your project.json.
#using Newtonsoft.Json
....
JsonConvert.DeserializeObject(json);
注意,使用 WebAPI 控制器不需要处理 JSON.
Note, using a WebAPI controller you don't need to deal with JSON.
Json.NET 已从 ASP.NET Core 中删除3.0 共享框架.
Json.NET has been removed from the ASP.NET Core 3.0 shared framework.
您可以在高性能 Utf8JsonReader
和 Utf8JsonWriter
之上使用新的 JSON 序列化器层.它从 JSON 反序列化对象并将对象序列化为 JSON.内存分配保持在最低限度,并支持使用 Stream 异步读取和写入 JSON.
You can use the new JSON serializer layers on top of the high-performance Utf8JsonReader
and Utf8JsonWriter
. It deserializes objects from JSON and serializes objects to JSON. Memory allocations are kept minimal and includes support for reading and writing JSON with Stream asynchronously.
首先,使用 System.Text.Json.Serialization
命名空间中的 JsonSerializer
类.请参阅文档 信息和样品.
To get started, use the JsonSerializer
class in the System.Text.Json.Serialization
namespace. See the documentation for information and samples.
在 ASP.NET Core 3.0 项目中使用 Json.NET:
To use Json.NET in an ASP.NET Core 3.0 project:
- 添加对 Microsoft.AspNetCore.Mvc.NewtonsoftJson 的包引用
- 更新 ConfigureServices 以调用 AddNewtonsoftJson().
services.AddMvc()
.AddNewtonsoftJson();
阅读Json.NET 支持aspnetcore-2.2&tabs=visual-studio" rel="noreferrer">从 ASP.NET Core 2.2 迁移到 3.0 Preview 2 了解更多信息.
Read Json.NET support in Migrate from ASP.NET Core 2.2 to 3.0 Preview 2 for more information.
这篇关于ASP.Net Core 中的 JSON 序列化/反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!