在ASP.NET Core API中将简单值转换为JSON [英] Converting simple value to JSON in ASP.NET Core API

查看:688
本文介绍了在ASP.NET Core API中将简单值转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我的ASP.NET Core API需要返回一个简单值,即boolintstring,即使在大多数情况下,我也会以JSON的形式返回复杂的对象/数组.

Sometimes my ASP.NET Core API needs to return a simple value i.e. bool, int or string even though in most cases, I return complex objects/arrays as JSON.

我认为出于一致性目的,最好将简单的值返回为JSON.将简单值(boolint)转换为JSON的最简单方法是什么?

I think for consistency purposes, it's a good idea to return even simple values as JSON. What's the easiest way to convert a simple value, whether it's bool or int into JSON?

我的标准控制器动作如下所示(请参阅下文),这使我能够返回状态码和数据.因此,我想坚持使用这种方法,而不是返回JsonResult.

My standard controller action looks like this -- see below -- which gives me the ability to return status codes as well as data. Therefore, I'd like to stick to that approach, rather than return JsonResult.

public async Task<IActionResult> Get()
{
   // Some logic
   return Ok(data);
}

如果不是JSON格式,我只是想找出将data转换为JSON的最简单方法.

I'm just trying to figure out the easiest way to convert my data into JSON, if it's not already in JSON format.

推荐答案

查看您的代码,我假设您的应用程序应该是一种服务,需要返回以JSON序列化的某种数据. 好消息是,ASP.NET Core已经包含一个数据序列化程序,可以为您完成这项工作. 您可能需要根据需要进行设置.

Looking at your code, I assume your application is supposed to be a service that needs to return some kind of data serialised in JSON. Well, good news is ASP.NET Core already includes a data serialiser that would do the job for you. You may need to set it up according to your needs.

例如,让我们假设以下数据类:

For example, let's assume the following data class:

public class Data {

    public string Name { get; }
    public string Value { get; }
    public bool IsValid { get; }

    public Data(string name, string value, bool isValid) {
        Name = name;
        Value = value;
        IsValid = isValid;
    }

}

然后在Controller中使用以下方法:

Then the following method in your Controller:

public async Task<IActionResult> Get() {
    var data = new Data("sample name", "this is a value", true);
    return Ok(data);
}

将返回:

{
    "name": "sample name",
    "value": "this is a value",
    "isValid": true
}

即使标准的序列化行为可能非常适合非常简单的实现,您也可能需要更多控制应用程序应如何对不同数据类型进行序列化(和反序列化),尤其是当这些数据类型与所需的方式不完全匹配时将数据呈现给客户端.在这种情况下,您可能需要使用自定义转换器.

Even thought the standard serialisation behaviour may fit fine for very simple implementations, you may need more control on how your different data types should be serialised (and deserialised) by your application, especially when those do not exactly match the way you want to present the data back to the client. In this case you may want to use Custom Converters.

您可以在ConfigureServices(IServiceCollection服务)方法中设置MVC时进行配置:

You can configure that when setting up MVC in the ConfigureServices(IServiceCollection services) method:

// Add framework services.
services.AddMvc().AddJsonOptions(jo => {

    // sample serialiser setup
    jo.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    jo.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
    jo.SerializerSettings.MissingMemberHandling = MissingMemberHandling.Error;

    // custom Converters
    jo.SerializerSettings.Converters.Add(new MyCustomConverter());

});

在这里,您可以阅读并了解有关设置的更多信息并使用自定义转换器.

Here you can read and learn more on how to setup and use Custom Converters.

这篇关于在ASP.NET Core API中将简单值转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆