how to set the value of a json path using json.net

后端 未结 1 596
梦谈多话
梦谈多话 2021-01-05 14:29

I am trying to set an arbitrary path in a JSON structure and I am having difficulty figuring out how to do a simple set value...

What I would like is some method lik

相关标签:
1条回答
  • 2021-01-05 15:00
        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();
        }
    
    0 讨论(0)
提交回复
热议问题