简体   繁体   中英

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.

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

Try LowercaseContractResolver instead

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

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
    }
}

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

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\" } }"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM