使用具有Newtonsoft的子对象创建以前为空的父对象

时间:2017-05-05 20:51:26

标签: json.net

使用NewtonsoftJson,并且在不知道整个“模型”的情况下,如果父元素尚不存在,如何创建新的父对象并设置子值?

现有父级

//The parent already exists, but the child does not.     
jobj["Parent1"]["Child"] = true; 

File.WriteAllText(mypath, JsonConvert.SerializeObject(joj, Formatting.Indented));

//output
//Successfully creates new child

新父母

//The parent does not exist, nor the child. 
//Throws null reference exception as jobj["Parent3"] doesn't exist
jobj["Parent3"]["Child"] = true;

File.WriteAllText(mypath, JsonConvert.SerializeObject(joj, Formatting.Indented));

JSON

{
"parent1": {
   "child": true
},
"parent2": {
  "child": true
},

1 个答案:

答案 0 :(得分:1)

嗯,您需要检查父项是否存在,如果不存在则创建它。

JToken parent = jobj["Parent3"];
if (parent == null)
{
    // parent object doesn't exist so create it
    parent = new JObject();
    jobj["Parent3"] = parent;
}
parent["Child"] = true;