如果不存在,如何通过路径添加JObject属性? [英] How to add JObject property by path if not exists?
问题描述
给出以下代码:
var context = JObject.FromObject(new
{
data = new
{
mom = "",
dad = "",
sibling = "",
cousin = ""
}
});
var path = "$.data.calculated";
var token = context.SelectToken(path);
token
将为空.因此,当然,尝试执行此操作会产生异常:
token
will be null. Thus, of course, trying this will produce an exception:
token.Replace("500");
我当然也看过其他有关如何向JObject
添加属性的示例,但它们似乎都需要您事先了解有关对象结构的知识.我需要做的是这样的:
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. What I need to do is something like this:
if (token == null)
{
context.Add(path);
token = context.SelectToken(r.ContextTarget);
}
然后我可以在新令牌上使用replace方法来设置其值.但是context.Add(path)抛出异常:
I could then use the replace method on the new token to set its' value. But context.Add(path) throws an exception:
"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;
}
这篇关于如果不存在,如何通过路径添加JObject属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!