首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JSON.net JObject添加为GrandChild而不是直接子

JSON.net JObject添加为GrandChild而不是直接子
EN

Stack Overflow用户
提问于 2017-04-19 02:46:12
回答 1查看 705关注 0票数 0

如果有从JObject到JProperty的Cast或部分副本,我就不会问这个问题了。

如果存在JObject.AddAsChild(otherJObj),它也可以工作。

下面的代码段生成一个GrandChild FavoriteFruit属性,但我想要一个直接子FavoriteFruit。FavoriteFruit.FavoriteFruit的双重深度属性不是我想要做的。

在我的情况下我控制着所有的代码。

在我的例子中,最明显的解决方案不起作用的细节是,我只有最后一个JObject来表示“FavoriteFruit”--我没有运行时访问生成特定的水果JObject实例的权限。

代码语言:javascript
复制
 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"
 //     }
 //   }
 // }
 //

下一段代码是这个特定情况下的可接受的解决方案.

代码语言:javascript
复制
   // 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向我展示了如何使用.First获取.First对象。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-19 03:13:49

您可以使用JObject的第一个属性、下一个属性和最后一个属性访问子属性。

代码语言:javascript
复制
parentPersonTopJObj.Add(childFavoritFruitJObj.First);

希望这句话能帮上你的忙。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43485454

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档