NewtonsoftJson을 사용하고 전체 '모델'을 모르는 채로 부모 개체가없는 경우 새 부모 개체를 만들고 자식 값을 설정하는 방법은 무엇입니까?Newtonsoft를 사용하여 자식 개체가 포함 된 이전 null null 부모 개체 만들기
JSON
{
"parent1": {
"child": true
},
"parent2": {
"child": true
},
NewtonsoftJson을 사용하고 전체 '모델'을 모르는 채로 부모 개체가없는 경우 새 부모 개체를 만들고 자식 값을 설정하는 방법은 무엇입니까?Newtonsoft를 사용하여 자식 개체가 포함 된 이전 null null 부모 개체 만들기
JSON
{
"parent1": {
"child": true
},
"parent2": {
"child": true
},
잘
//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));
부모
//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
새로운 부모에게 기존, 당신은 확인해야 부모가 존재하는지 여부, 부모가 존재하지 않는 경우 생성.
JToken parent = jobj["Parent3"];
if (parent == null)
{
// parent object doesn't exist so create it
parent = new JObject();
jobj["Parent3"] = parent;
}
parent["Child"] = true;
새 JProperty를 추가하려면 JProperty 생성자 내에 JToken.FromObject를 추가해야합니다.
예를 들어
jobj.Add(new JProperty("parent3", JToken.FromObject(new Parent { Child = true})));
감사 브라이언, 내 방식에 대한 대안. 나는 당신이 새로운 JProperty 생성자에 전달 된 객체를 나타 내기 위해 POCO를 생성 할 필요가 없다는 장점을 가지고있어 유용하다고 생각합니다. – ManxJason