【问题标题】:JSON.net JObject Adds as GrandChild instead of Direct ChildJSON.net JObject 添加为 GrandChild 而不是 Direct Child
【发布时间】: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 输出中删除一层嵌套。

标签: c# json.net


【解决方案1】:

您可以使用 JObject 的 First、Next 和 Last 属性访问 child。

parentPersonTopJObj.Add(childFavoritFruitJObj.First);

希望这条线路能帮助您满足您的需要。

【讨论】:

  • 这会操纵输入以获得所需的结果。您的解决方案似乎很明显,但在我的情况下,我无法在原始 JObject 退出之前的调用之前对其进行操作。我正在寻找一种将 JObject 作为子项添加到现有 JObject 的方法。在您的解决方案中,您没有使用 childFavoritFruitJObj。我可以在 childFavoriteFruitJObj 退出呼叫之后和 .Add() 之前对其进行操作
  • 修改了我的答案。
  • 感谢您坚持第二次调查此问题。真的很感激。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多