C# ASP.Net Core 中的 JSON 序列化/反序列化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29841503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 04:19:08  来源:igfitidea点击:

JSON serialization/deserialization in ASP.Net Core

c#jsonasp.net-core

提问by Jakub Wisniewski

Since there is no JavaScriptSerializer, what native implementation can be used to handle this?

既然没有JavaScriptSerializer,那么可以使用什么本机实现来处理这个问题?

I noticed JsonResultand I can format data to JSON with this, but how do I deserialize?

我注意到JsonResult并且我可以用这个将数据格式化为 JSON,但是我如何反序列化?

Or maybe I am missing some dependencies in project.json?

或者我可能缺少一些依赖项project.json

采纳答案by agua from mars

You can use Newtonsoft.Json, it's a dependency of Microsoft.AspNet.Mvc.ModelBindingwhich is a dependency of Microsoft.AspNet.Mvc. So, you don't need to add a dependency in your project.json.

您可以使用Newtonsoft.Json,它的依赖项Microsoft.AspNet.Mvc.ModelBinding是 的依赖项Microsoft.AspNet.Mvc。因此,您无需在 project.json 中添加依赖项。

#using Newtonsoft.Json
....
JsonConvert.DeserializeObject(json);

Note, using a WebAPI controller you don't need to deal with JSON.

请注意,使用 WebAPI 控制器不需要处理 JSON。

UPDATE ASP.Net Core 3.0

更新 ASP.Net 核心 3.0

Json.NEThas been removed from the ASP.NET Core 3.0 shared framework.

Json.NET已从 ASP.NET Core 3.0 共享框架中删除。

You can use the new JSON serializer layers on top of the high-performance Utf8JsonReaderand 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.

您可以在高性能Utf8JsonReaderUtf8JsonWriter. 它从 JSON 反序列化对象并将对象序列化为 JSON。内存分配保持最小,并支持异步读取和写入 JSON 与 Stream。

To get started, use the JsonSerializerclass in the System.Text.Json.Serializationnamespace. See the documentationfor information and samples.

首先,使用命名空间中的JsonSerializerSystem.Text.Json.Serialization。有关信息和示例,请参阅文档

To use Json.NET in an ASP.NET Core 3.0 project:

在 ASP.NET Core 3.0 项目中使用 Json.NET:

    services.AddMvc()
        .AddNewtonsoftJson();

Read Json.NET supportin Migrate from ASP.NET Core 2.2 to 3.0 Preview 2for mor informations

阅读Migrate from ASP.NET Core 2.2 to 3.0 Preview 2 中的Json.NET 支持以获取更多信息

回答by NoloMokgosi

.net core

.net核心

using System.Text.Json;

using System.Text.Json;

To serialize

序列化

var jsonStr = JsonSerializer.Serialize(MyObject)

Deserialize

反序列化

var weatherForecast = JsonSerializer.Deserialize<MyObject>(jsonStr);

For more information about excluding properties and nulls check out This Microsoft side

有关排除属性和空值的更多信息,请查看 Microsoft 端