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

Time:12-26

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

CodePudding user response:

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.

CodePudding user response:

.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;
    );
  • Related