使用Json.net对Json进行遍历

公司使用了一种伪Json, 当value为字符串并且以"@"开头时, 要替换成真实的值, 比如{"name":"@countryName"}, 那么就要把@countryName替换掉, 这就涉及到使用Json.net进行遍历
以前都是直接写相应的class然后直接Newtonsoft.Json.JsonConvert.DeserializeObject<T>()就可以了, 遍历的方法还是很不好找, 所以给共享出来

private static void RecursivelyReplaceVariable(JToken jToken, Dictionary<string, string> variables)
{
    if (jToken is JValue)
    {
        return;
    }
    var childToken = jToken.First;
    while (childToken != null)
    {
        if (childToken.Type == JTokenType.Property)
        {
            var p = (JProperty)childToken;
            var valueType = p.Value.Type;

            if (valueType == JTokenType.String)
            {

                var value = p.Value.ToString();
                if (value.StartsWith("@"))
                {
                    if (!variables.TryGetValue(value, out value))
                    {
                        throw new Exception($"Variable {value} not defined");
                    }
                    p.Value = value;
                }
            }
            else if (valueType == JTokenType.Object)
            {
                RecursivelyReplaceVariable(p.Value, variables);
            }
            else if (valueType == JTokenType.Array)
            {
                foreach (var item in (JArray)p.Value)
                {
                    RecursivelyReplaceVariable(item, variables);
                }
            }
        }
        childToken = childToken.Next;
    }
}

另外一种方法

var properties = jObject.Properties();
foreach (var property in properties)
{
    var valueType = property.Value.Type;
    if (valueType== JTokenType.Object)
    {
        ReplaceValue((JObject)property.Value );
    }
    else if (valueType== JTokenType.String)
    {
        property.Value = "...";
    }
    else if (valueType== JTokenType.Array)
    {
        var k=property.Value.First();
        foreach (var item in (JArray)property.Value)
        {
            ReplaceValue((JObject)item);
        }
    }
}

Json.net中一些基础类的继承关系

JObject、JProperty、JArray、JConstructor继承自JContainer(abstract)
JValue、JContainer继承自JToken(abstract)

原文地址:https://www.cnblogs.com/zhouandke/p/9287107.html