如果沒有從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
您要查找的預期輸出是什麼? –
我渴望一個FavoriteFruit對象。我想從FavoriteFruit輸出中刪除一層嵌套。 –