【问题标题】:how to set the value of a json path using json.net如何使用 json.net 设置 json 路径的值
【发布时间】:2015-01-29 23:39:19
【问题描述】:

我正在尝试在 JSON 结构中设置任意路径,但我很难弄清楚如何进行简单的设置值...

我想要的是某种方法,例如 SetValue(path,value),它的操作类似于 SelectToken,但如果路径不存在则创建路径并设置值。

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" }}
}

我所说的global.defaults.sort路径实际上是{ global: { defaults: { sort: { true } } } }

【问题讨论】:

    标签: c# json json.net


    【解决方案1】:
        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();
        }
    

    【讨论】:

    • 谢谢,但它需要修改以处理 JSON 数组,我会在完成后发布代码示例
    • 所以答案本质上是:“Newtonsoft 不做,但你可以自己解释 jsonpath”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-21
    • 2019-03-26
    相关资源
    最近更新 更多