Home > Back-end >  .NET 6 - Change Json Property Casing
.NET 6 - Change Json Property Casing

Time:12-07

How can I change the casing of the property names of a json without performing model binding? JsonElement serialization ignores PropertyNaming JsonSerializer options as is also confirmed here: https://github.com/dotnet/runtime/issues/61843 The suggested use of JsonNode/JsonObject results in the same behavior.

Any hints how I can accomplish this?

As example I want to change this:

{
    "MyPoperty" : 5,
    "MyComplexProperty" : {
        "MyOtherProperty": "value",
        "MyThirdProperty": true
    }
}

to this:

{
    "myPoperty" : 5,
    "myComplexProperty" : {
        "myOtherProperty": "value",
        "myThirdProperty": true
    }
}

Cheers.

CodePudding user response:

not depend on Newtonsoft json but in the case of multi-layer objects

var json = @"{""ShouldWindUpAsCamelCase"":""does it?""}";
var obj = JsonSerializer.Deserialize<Dictionary<string,string>>(json);
var dic = new Dictionary<string, string>();
foreach (var item in obj)
{
    dic.Add(item.Key.FirstCharToLower(), item.Value);
}
var serialized = System.Text.Json.JsonSerializer.Serialize(dic);
Console.WriteLine(serialized);

FirstCharToLower() function

 public static string FirstCharToLower(this string input)
        {
            if (String.IsNullOrEmpty(input))
                return input;
            string str = input.First().ToString().ToLower()   input.Substring(1);
            return str;
        }

#output

{"shouldWindUpAsCamelCase":"does it?"}

CodePudding user response:

I think you try to use Newtonsoft json

class Person
{
    public string UserName { get; set; }
    public int Age { get; set; }
}

coding

static void Main(string[] args)
{
    Person person = new Person();
    person.UserName = "Bob";
    person.Age = 20;

    var serializerSettings = new JsonSerializerSettings();
    serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    var json = JsonConvert.SerializeObject(person, serializerSettings);
    Console.WriteLine(json);
}

output

{"userName":"Bob","age":20}
  • Related