公司使用了一種僞Json, 當value爲字符串而且以"@"開頭時, 要替換成真實的值, 好比{"name":"@countryName"}, 那麼就要把@countryName替換掉, 這就涉及到使用Json.net進行遍歷
之前都是直接寫相應的class而後直接Newtonsoft.Json.JsonConvert.DeserializeObject<T>()就能夠了, 遍歷的方法仍是很很差找, 因此給共享出來spa
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; } }
另一種方法.net
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中一些基礎類的繼承關係code
JObject、JProperty、JArray、JConstructor繼承自JContainer(abstract)
JValue、JContainer繼承自JToken(abstract)blog