简体   繁体   中英

How to convert key value from result to uppercase in an ASP.NET Core 3.1 Web API

Model class:

public class User
{
    public string NS_ID { get; set; }
    public string TONV_ABC { get; set; }
    public string NAME_ABC { get; set; }
    public string MAABC { get; set; }
}

Result json when testing in Postman:

    "nS_ID": "",
    "tonV_ABC": "",
    "namE_ABC": "",
    "maabc": "F02",

This is the result I want:

    "NS_ID": "",
    "TONV_ABC": "",
    "NAME_ABC": "",
    "MAABC": "F02",

This is my API:

    [HttpGet]
    [Route("test")]
    public ActionResult test()
    {
        User u = new User();
        u.NS_ID = "";
        u.TONV_ABC = "";
        u.NAME_ABC = "";
        u.MAABC = "F02";
        return Ok(u);
    }

Please help me

I try convert but it's not working

you can try to deserialize the JSON string to a Dictionary<string, object> . then create another Dictionary. iterate over the first dictionary and add all the key-value pairs to the new dictionary why making the key to upper case using the ToUpper() method. then serialize the new dictionary to the JSON string.

Sample code:

Dictionary<string, object> jsonDictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);
Dictionary<string, object> result = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> kvp in jsonDictionary)
{
    result.Add(kvp.Key.ToUpper(), kvp.Value);
}
string resultJson = JsonConvert.SerializeObject(result);

Note : I have used NewtonSoft.json . you can get it from the Nuget package manager.

.net 7 : You just need to add the following configuration to Program.cs :

builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
         options.JsonSerializerOptions.PropertyNamingPolicy = null;
    });

.net core 3.1:

add the following configuration to startup.cs :( ConfigureServices(IServiceCollection services) )

services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.PropertyNamingPolicy= null;
    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM