Confusion in getting Parent from JToken

若如初见. 提交于 2019-12-05 03:43:30

The hierarchy you're traversing is how Json.net structures the objects, it is not representative of the json string itself.

Relative to the ProductA object (well, one up), this is how you get down to ProductC:

JProperty: "ProductA"
 -> JObject (ProductA object)
     -> JProperty: "children"
         -> JObject (children object)
             -> JProperty: "ProductC"
                 -> JObject (ProductC object)  *you are here

So if you look at it this way, you should see that you are actually accessing the JProperty "ProductA" (5 parents up), not the object itself. As you might have noticed, JObjects do not have a name, you're getting the name of the JProperty.

I can't tell you how exactly you can access it as it is described in the json string, it doesn't appear to be an option. But you could of course write some helper methods to get them for you.

Here's one implementation to get the parent object. I don't know what other JTokens we'd encounter that we'd want to skip, but this is a start. Just pass in the token you want to get the parent of. Pass in an optional parent number to indicate which parent you want.

JToken GetParent(JToken token, int parent = 0)
{
    if (token == null)
        return null;
    if (parent < 0)
        throw new ArgumentOutOfRangeException("Must be positive");

    var skipTokens = new[]
    {
        typeof(JProperty),
    };
    return token.Ancestors()
        .Where(a => skipTokens.All(t => !t.IsInstanceOfType(a)))
        .Skip(parent)
        .FirstOrDefault();
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!