It seems that the intended behaviour of JValue.ToString()
is to return the enclosed value as a string rather than encode to JSON. Instead JValue.ToString(IFormatProvider)
should be used to produce a valid JSON encoded string.
https://github.com/JamesNK/Newtonsoft.Json/issues/266
However, in my particular case it seems to make better sense to retain the Json.NET representation since this avoids reparsing the same JSON content multiple times:
Groups = new Dictionary<string, Dictionary<string, JToken>>();
foreach (var jsonGroup in JObject.Parse(jsonText)) {
var group = new Dictionary<string, JToken>();
Groups[jsonGroup.Key] = group;
foreach (var jsonProperty in jsonGroup.Value.Children<JProperty>())
group[jsonProperty.Name] = jsonProperty.Value;
}
And then, instead of parsing these sub-structures with JObject.Parse
I can use JToken.ToObject<T>
to convert them into the desired representation:
bool myValue = Groups["Group A"]["Prop B"].ToObject<bool>();