A. Gladkiy
A. Gladkiy

Reputation: 3450

json properties to lower case 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.

Upvotes: 4

Views: 8626

Answers (5)

Arsen Khachaturyan
Arsen Khachaturyan

Reputation: 8330

Extending Anton Semenov answer for cases when JSON can contain an Array of Objects:

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);

        if (property.Value.Type == JTokenType.Array)
        {
            var arr = JArray.Parse(property.Value.ToString());
            foreach (var pr in arr)
            {
                ChangePropertiesToLowerCase((JObject)pr);
            }

            property.Value = arr;
        }

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

Upvotes: 1

Impworks
Impworks

Reputation: 2818

All other solutions here modify the original object. Here's an immutable version which returns a new object with lowercase properties:

public static class JsonExtensions
{
    public static JToken ToLowerRecursive(this JToken token)
    {
        if (token is JObject jobj)
            return new JObject(jobj.Properties().Select(x => new JProperty(x.Name.ToLowerInvariant(), x.Value.ToLowerRecursive())));

        if (token is JArray jarr)
            return new JArray(jarr.Select(x => x.ToLowerRecursive()));

        return token;
    }
}

Upvotes: 1

Anton Semenov
Anton Semenov

Reputation: 6347

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);

Upvotes: 4

bar-tech
bar-tech

Reputation: 41

This is easy way without Regex. Replace every [{ "A] with [{ "a]

var json = "{ \"Client\": { \"Name\": \"John\" } }";
var newJson = string.Empty;

foreach (var w in json.Split(new[] { "{ \"" }, StringSplitOptions.RemoveEmptyEntries))
{
    if (w[0] != null)
    {
        newJson += "{ \"" + (w[0].ToString().ToLower()) + w.Remove(0,1);
    }
}

result:

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

Upvotes: -1

tchelidze
tchelidze

Reputation: 8318

Try LowercaseContractResolver instead

var settings = new JsonSerializerSettings();
settings.ContractResolver = new LowercaseContractResolver();
var json = JsonConvert.DeserializeObject(input.DataJson, settings);

Upvotes: 1

Related Questions