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

Tim*_*erz 6 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.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" }}
}
Run Code Online (Sandbox Code Playgroud)

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

Tim*_*erz 9

    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();
    }
Run Code Online (Sandbox Code Playgroud)