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

点点圈 提交于 2019-12-19 02:47:46

问题


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 like, SetValue(path,value) which operates like SelectToken, but creates the 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 global.defaults.sort path is actually { global: { defaults: { sort: { true } } } }


回答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();
    }


来源:https://stackoverflow.com/questions/17455052/how-to-set-the-value-of-a-json-path-using-json-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!