【发布时间】:2017-04-19 02:46:12
【问题描述】:
如果有从 JObject 到 JProperty 的 Cast 或部分副本,我不会问这个问题。
如果 JObject.AddAsChild(otherJObj) 存在,它也可以工作。
下面的 sn-p 生成一个 GrandChild FavoriteFruit 属性,但我想要一个 Direct Child 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 运算符有一个不会创建大子场景的单一参数属性版本。更重要的是,Sailesh 向我展示了如何使用 .First 取出 JToken 对象
【问题讨论】:
-
您要寻找的预期输出是什么?
-
我想要一个 FavoriteFruit 对象。我想从 FavoriteFruit 输出中删除一层嵌套。