C#中将JSON属性名转换为小写

3

我从客户端获取JSON字符串:

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

但是为了进一步处理,我需要以下JSON:

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

我尝试过类似的方法,但没有起到帮助作用:

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

并且

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

JSON是动态对象,所以我不知道有哪些属性。我该如何在C#中实现呢?可以使用Newtonsoft.Json或者Xml。

5个回答

3
如果我理解正确的话,您需要修改Json字符串中的属性,而不是将Json转换为对象。

在这种情况下,您可以尝试将Json解析为JObject,并替换该对象中的属性。

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

示例:

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

var stringWithLowerCaseProperties = jobj.ToString(Formatting.None);

1
尝试使用 LowercaseContractResolver 代替。
var settings = new JsonSerializerSettings();
settings.ContractResolver = new LowercaseContractResolver();
var json = JsonConvert.DeserializeObject(input.DataJson, settings);

1
它也没有帮助。 - A. Gladkiy

1

扩展Anton Semenov的答案,适用于JSON可以包含对象数组的情况:

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

0

这里的所有其他解决方案都修改了原始对象。这是一个不可变版本,它返回一个具有小写属性的新对象:

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

-1

这是一个简单的方法,不需要使用正则表达式。将每个 [{ "A] 替换为 [{ "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);
    }
}

结果:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接