1

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.

BasiK
  • 546
  • 6
  • 20
  • seems like your question has already an answer here: https://stackoverflow.com/questions/58570189/is-there-a-built-in-way-of-using-snake-case-as-the-naming-policy-for-json-in-asp/ – Just Shadow Dec 06 '21 at 11:30
  • No - that solution requires model binding. The serialization does not take naming policy or custom converters into account when serializing JsonElements. – BasiK Dec 06 '21 at 12:47

2 Answers2

-1

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}
wangyou
  • 35
  • 4
-1

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?"}
wangyou
  • 35
  • 4
  • Thanks for the suggestion, but this will also not work. This basically binds to a flat dictionary. So it doesn't allow complex objects. I did find a solution after all, but it is far from ideal: https://stackoverflow.com/questions/57263017/how-to-get-newtonsoft-to-camelcase-object-properties - uses newtonsoft and expandoObject. – BasiK Dec 07 '21 at 11:01
  • Well LET me try a few more ways and I'll let you know – wangyou Dec 07 '21 at 11:50