Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json properties to lower case c#

Tags:

json

c#

I'm getting from client json string:

{ "Client": { "Name": "John" } }

but for the further handling I need the following json:

{ "client": { "name": "John" } }

I tried something like that, but it didn't help:

public class LowerCaseNamingStrategy : NamingStrategy
{
    protected override string ResolvePropertyName(string name)
    {
        return name.ToLower();
    }
}

and

var settings = new JsonSerializerSettings();
settings.ContractResolver = new DefaultContractResolver { NamingStrategy = new LowerCaseNamingStrategy() };
var json = JsonConvert.DeserializeObject(input.DataJson, settings);

JSON is dynamic object, so I don't know properties are there. How can I do that with c#? With using Newtonsoft.Json or may be with using Xml.

like image 947
A. Gladkiy Avatar asked Oct 26 '25 03:10

A. Gladkiy


1 Answers

If I understood you correctly, you need to modify properties in your Json string, but not convert the Json into object.

In this case you can try to parse Json into JObject and replace properties in that object.

    private static void ChangePropertiesToLowerCase(JObject jsonObject)
    {
        foreach (var property in jsonObject.Properties().ToList())
        {
            if(property.Value.Type == JTokenType.Object)// replace property names in child object
                ChangePropertiesToLowerCase((JObject)property.Value);

            property.Replace(new JProperty(property.Name.ToLower(),property.Value));// properties are read-only, so we have to replace them
        }
    }

sample:

var jsonString = @"{ ""Client"": { ""Name"": ""John"" } }";
var jobj = JObject.Parse(jsonString, new JsonLoadSettings());
ChangePropertiesToLowerCase(jobj);

var stringWithLowerCaseProperties = jobj.ToString(Formatting.None);
like image 122
Anton Semenov Avatar answered Oct 28 '25 17:10

Anton Semenov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!