Converting simple value to JSON in ASP.NET Core API

大兔子大兔子 提交于 2020-01-06 08:12:18

问题


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.

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?

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);
}

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


回答1:


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;
    }

}

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);
}

would return:

{
    "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.

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.



来源:https://stackoverflow.com/questions/49970576/converting-simple-value-to-json-in-asp-net-core-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!