如果有从JObject到JProperty的Cast或部分副本,我就不会问这个问题了。
如果存在JObject.AddAsChild(otherJObj),它也可以工作。
下面的代码段生成一个GrandChild FavoriteFruit属性,但我想要一个直接子FavoriteFruit。FavoriteFruit.FavoriteFruit的双重深度属性不是我想要做的。
在我的情况下我控制着所有的代码。
在我的例子中,最明显的解决方案不起作用的细节是,我只有最后一个JObject来表示“FavoriteFruit”--我没有运行时访问生成特定的水果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向我展示了如何使用.First获取.First对象。
发布于 2017-04-19 03:13:49
您可以使用JObject的第一个属性、下一个属性和最后一个属性访问子属性。
parentPersonTopJObj.Add(childFavoritFruitJObj.First);希望这句话能帮上你的忙。
https://stackoverflow.com/questions/43485454
复制相似问题