[英]How to add JObject property by path if not exists?
Given the following code: 给出以下代码:
var context = JObject.FromObject(new
{
data = new
{
mom = "",
dad = "",
sibling = "",
cousin = ""
}
});
var path = "$.data.calculated";
var token = context.SelectToken(path);
token
will be null. token
将为null。 Thus, of course, trying this will produce an exception: 因此,当然,尝试这样做将产生异常:
token.Replace("500");
I've seen other examples about how to add properties to a JObject
, of course, but they all seem like you have to know something about the object structure beforehand. 我当然也看过其他有关如何向JObject
添加属性的JObject
,但它们似乎都需要您事先了解有关对象结构的知识。 What I need to do is something like this: 我需要做的是这样的:
if (token == null)
{
context.Add(path);
token = context.SelectToken(r.ContextTarget);
}
I could then use the replace method on the new token to set its' value. 然后,我可以对新令牌使用replace方法设置其值。 But context.Add(path) throws an exception: 但是context.Add(path)抛出一个异常:
"Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject."
How can I dynamically add a property using a full path like this, without knowing the existing object structure? 如何在不知道现有对象结构的情况下使用像这样的完整路径动态添加属性?
While this isn't a catch-all (won't correctly do arrays for example), it does handle the above simple case and should provide for multiple levels into the hierarchy. 虽然这不是万能的(例如,不能正确地处理数组),但它确实可以处理上述简单情况,并应在层次结构中提供多个级别。
if (token == null)
{
var obj = CreateObjectForPath(path, newValue);
context.Merge(obj);
}
And the meat of the roll-your-own part: 和自己动手的部分的肉:
private JObject CreateObjectForPath(string target, object newValue)
{
var json = new StringBuilder();
json.Append(@"{");
var paths = target.Split('.');
var i = -1;
var objCount = 0;
foreach (string path in paths)
{
i++;
if (paths[i] == "$") continue;
json.Append('"');
json.Append(path);
json.Append('"');
json.Append(": ");
if (i + 1 != paths.Length)
{
json.Append("{");
objCount++;
}
}
json.Append(newValue);
for (int level = 1; level <= objCount; level++)
{
json.Append(@"}");
}
json.Append(@"}");
var jsonString = json.ToString();
var obj = JObject.Parse(jsonString);
return obj;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.