2017-04-19 18 views
0

如果沒有從JObject到JProperty我就不會問這個問題,一個演員或部分複製。JSON.net JObject再添作爲如GrandChild,而不是直接子

一個JObject.AddAsChild(otherJObj)也將工作,如果它的存在。

下面的代碼片斷產生一個孫子FavoriteFruit屬性,但我希望有一個直接子FavoriteFruit。 FavoriteFruit.FavoriteFruit雙深房產不是我想要做的。

我控制所有的代碼在我的處境。

使我最明顯的解決方案在我的情況下不起作用的細節是,我只獲得最終的JObject來表示「FavoriteFruit」 - 我沒有運行時訪問生成該特定Favorite Fruit JObject實例的內容。

JObject childFavoritFruitJObj = new JObject(); // child JObject 
if (true) 
{ 
    JProperty childFruitNameJProp = new JProperty("FruitName", "Pear"); 
    JObject childFruitInfoJObj = new JObject(); 
    childFruitInfoJObj.Add(childFruitNameJProp); 
    childFavoritFruitJObj.Add("FavoriteFruit", childFruitInfoJObj); 
    // only JObject childFavoritFruitJObj remains in scope 
} 

JObject parentPersonTopJObj = new JObject(); // Final Parent JObject 
JProperty parentPersonNameJProp = new JProperty("PersonName", "John Doe"); 

parentPersonTopJObj.Add(parentPersonNameJProp); 
parentPersonTopJObj.Add("FavoriteFruit", childFavoritFruitJObj); // INCORRECT 

Console.WriteLine(parentPersonTopJObj.ToString()); 

// Final Result - Not As Desired 
// There are TWO "FavoriteFruit" Objects 
// FavoriteFruit is a GRAND CHILD not a Child as wanted 
// { 
// "PersonName": "John Doe", 
// "FavoriteFruit": { 
//  "FavoriteFruit": { 
//  "FruitName": "Pear" 
//  } 
// } 
// } 
// 

這下一個代碼是接受的解決方案對於此特定情況。

// This is the undesired BAD scenario - this was the original question 
    parentPersonTopJObj.Add("FavoriteFruit", childFavoritFruitJObj); 

    // This is the accepted SOLUTION proposed below by Sailesh 
    JProperty propFirst = null; 
    propFirst = (JProperty)childFavoritFruitJObj.First; 
    parentPersonTopJObj.Add(propFirst); 

    // the above works in my specific case as I am guarnteed 
    // a single property name at the top of my JObject. If you had 
    // multiple Properties at the top this would not work.; 

重載.Add運營商具有不創造盛大孩子的場景單一PARAM屬性的版本。更重要的是Sailesh教我如何獲得JToken對象了與.First

+0

您要查找的預期輸出是什麼? –

+0

我渴望一個FavoriteFruit對象。我想從FavoriteFruit輸出中刪除一層嵌套。 –

回答

1

可以使用的第一個訪問的孩子,Next和JObject的最新特性。

parentPersonTopJObj.Add(childFavoritFruitJObj.First); 

希望這條線可以幫助您滿足您的需求。

+0

這將操縱輸入以獲得期望的結果。你的解決方案似乎很明顯,但在我的情況下,我不能操縱原來的JObject,它在前面的調用結束之前。我正在尋找一種將JObject作爲子項添加到現有JObject的方法。在你的解決方案中,你沒有使用childFavoritFruitJObj。我可以操作childFavoriteFruitJObj,在它出來之後,在我加入()之後, –

+0

修改了我的答案。 –

+0

感謝您第二次繼續關注此事。真的很感激。 –

相關問題