使用分隔的路径/键将复杂对象添加到JObject [英] Adding a complex object to JObject using a delimited path/key
问题描述
我正在与Jsons一起工作,而Jsons我不了解它们的高级结构.例如:
I am working with Jsons which I don't know their structure in advanced. Just for example:
{
"OrganizationData": {
"Org1": {
"Name": "Rega And Dodli",
"EmployessNum": "100000000"
},
"Org2": {
"Name": "Sami And Soso",
"EmployessNum": "2"
}
}
}
我目前正在使用SelectToken
方法获取值,我可以将键和子键传递给该方法,
I'm currently getting values by using the SelectToken
method to which I can pass a key with a sub key like this:
var token = myJObject.SelectToken("OrganizationData.Org1")
这很好.现在,我想使用类似这样的字符串向JSON添加新条目:
This works fine. Now I want to add a new entry to the JSON using a string like that, something like:
myJObject.Add("OrganizationData.Org3", myValueJson);
,但是直接调用add只是将一个新密钥添加到名为"OrganizationData.Org3"的json中.而不是创建一个称为"Org3"的新子密钥.在"OrganizationData"内部就像当前的"Org1"和"Org2".
but calling add like that directly just adds a new key to the json called "OrganizationData.Org3" and not creating a new sub key called "Org3" inside "OrganizationData" like the current "Org1" and "Org2".
如何添加带有所需分隔字符串的新值?
How can I add a new value with a delimited string like needed?
推荐答案
JSON没有子键或定界键. OrganizationData.Org1
是LINQ to JSON搜索表达式,不是子项.
JSON doesn't have subkeys or delimited keys. OrganizationData.Org1
is a LINQ to JSON search expression, not a subkey.
要添加Org3
,您可以使用多种可用于修改JSON对象的方法之一.您可以将子元素添加到OrganizationData
或将兄弟元素添加到其他Org
节点之一.
To add Org3
you can use one of the many ways available to modify a JSON object. You can add a child element to OrganizationData
or a sibling to one of the other Org
nodes.
要将子元素添加到节点,可以使用.SelectToken("OrganizationData")
(如果尚未对其进行引用),然后使用JObject.Add
添加新节点.您必须先将结果转换为JObject
,因为SelectToken
返回JToken
.如果有可能OrganizationData
是数组,则也必须检查类型.
To add a child element to a node, you could use .SelectToken("OrganizationData")
if you don't already have a reference to it, and use JObject.Add
to add the new node. You'll have to cast the result to JObject
first, as SelectToken
returns a JToken
. If there's a chance that OrganizationData
is an array, you'll have to check the type too.
例如:
var token = myJObject.SelectToken("OrganizationData");
if(token is JObject orgObj)
{
orgObj.Add("Org3",myValueJson);
}
使用未知路径
如果在运行时指定了路径,则同样的方法起作用.在这种情况下,只需使用
The same thing works if the path is specified at runtime. In this case, all that's needed is to separate the last part from the rest of the path, perhaps using String.LastIndexOf`:
var lastDot=path.LastIndexOf('.');
if (lastDot<0)
{
//Oops! There's no dot. What do we do now?
}
var parent=path.Substring(0,lastDot);
var key=path.Substring(lastDot+1);
var token = myJObject.SelectToken(parent);
if(token is JObject orgObj)
{
orgObj.Add(key,myValueJson);
}
如果路径中不包含点,则必须决定要怎么做.这是无效的路径吗?还是应该在根对象下添加一个新对象?
You'll have to decide what to do if the path contains no dot. Is this an invalid path? Or should a new object be added under the root object?
这篇关于使用分隔的路径/键将复杂对象添加到JObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!