How to set json path value using json.net

I'm trying to set an arbitrary path in a JSON structure, and it's hard for me to figure out how to make a simple value ...

I would like to use some SetValue method (path, value) that works like SelectToken, but creates a path if it does not exist and sets the value.

public void SetPreference(string username, string path, string value) { var prefs = GetPreferences(username); var jprefs = JObject.Parse(prefs ?? @"{}"); var token = jprefs.SelectToken(path); if (token != null) { // how to set the value of the path? } else // how to add the path and value, example {"global.defaults.sort": { "true" }} } 

what I mean by the end of global.defaults.sort is actually { global: { defaults: { sort: { true } } } }

+4
source share
1 answer
  public string SetPreference(string username, string path, string value) { if (!value.StartsWith("[") && !value.StartsWith("{")) value = string.Format("\"{0}\"", value); var val = JObject.Parse(string.Format("{{\"x\":{0}}}", value)).SelectToken("x"); var prefs = GetPreferences(username); var jprefs = JObject.Parse(prefs ?? @"{}"); var token = jprefs.SelectToken(path) as JValue; if (token == null) { dynamic jpart = jprefs; foreach (var part in path.Split('.')) { if (jpart[part] == null) jpart.Add(new JProperty(part, new JObject())); jpart = jpart[part]; } jpart.Replace(val); } else token.Replace(val); SetPreferences(username, jprefs.ToString()); return jprefs.SelectToken(path).ToString(); } 
+8
source

Source: https://habr.com/ru/post/1489559/


All Articles