Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用json.net设置json路径的值_C#_Json_Json.net - Fatal编程技术网

C# 如何使用json.net设置json路径的值

C# 如何使用json.net设置json路径的值,c#,json,json.net,C#,Json,Json.net,我试图在JSON结构中设置任意路径,但我很难弄清楚如何进行简单的设置值 我想要的是像SetValue(path,value)这样的方法,它的操作方式类似于SelectToken,但如果路径不存在,则创建路径并设置值 public void SetPreference(string username, string path, string value) { var prefs = GetPreferences(username); var jprefs = JObject.Pa

我试图在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
path实际上是
{global:{defaults:{sort:{true}}}}}

谢谢,但它需要修改才能处理JSON数组,我会在完成后发布代码示例,所以答案基本上是:“Newtonsoft不做,但您可以自己解释jsonpath”
    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();
    }