从JSONPath构建JObject [英] Build JObject from JSONPath

查看:97
本文介绍了从JSONPath构建JObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用.NET的Newtonsoft JSON库有些陌生.有什么方法可以从JSONPath创建JObject或JToken吗?

I'm a bit new to using the Newtonsoft JSON library for .NET. Is there any way to create a JObject or JToken from a JSONPath?

例如,如下所示.

string jsonPath = "$.ArrayA[0].ArrayB[0].Property";
JObject jObj = JObject.FromJSONPath(jsonPath); // SOMETHING LIKE THIS

结果将是一个看起来像这样的JObject或JToken.

The result would be a JObject or JToken that looks like this.

{
    "ArrayA": [{
        "ArrayB": [{
            "Property": ""
        }]
    }
}

推荐答案

否.

如果您已有一些JSON,则可以将其解析为JToken,然后使用 SelectTokens JsonPath表达式.例如:

If you have some existing JSON, you can parse it to a JToken and then select one or more descendant JTokens from it using SelectToken or SelectTokens with a JsonPath expression. For example:

string json = @"{ ""ArrayA"": [{ ""ArrayB"": [{ ""Property"": ""foo"" }] }] }";
JToken token = JToken.Parse(json);
JToken fooToken = token.SelectToken("$..Property");
Console.WriteLine(fooToken.ToString());    // prints "foo"

您还可以手动构建JTokens的嵌套结构.例如,您可以像这样在问题中创建JObject:

You can also manually build a nested structure of JTokens. For example, you can create the JObject in your question like this:

var obj = new JObject(new JProperty("ArrayA", new JArray(
             new JObject(new JProperty("ArrayB", new JArray(
                new JObject(new JProperty("Property", ""))))))));

但是,没有内置方法可以通过JsonPath表达式来创建JToken.您将需要滚动自己的方法来执行类似的操作.但是请记住,JsonPath被设计为查询机制.它不能清晰地映射到新对象的创建.这是您需要考虑的一些问题:

However, there is no built-in way to create a JToken from nothing but a JsonPath expression. You would need to roll your own method to do something like that. But keep in mind that JsonPath was designed as a query mechanism; it doesn't map cleanly to creation of new objects. Here are some issues you would need to think about:

  • 在您的示例表达式$.ArrayA[0].ArrayB[0].Property中,Property是什么类型?它是字符串,数字,布尔值,对象还是空数组?您将如何指定呢?
  • 您如何指定具有多个属性的对象的创建?
  • $..book[(@.length-1)]这样的表达式会创建什么?
  • In your example expression, $.ArrayA[0].ArrayB[0].Property, what type is Property? Is it string, number, boolean, object or an empty array? How would you specify that?
  • How would you specify creation of an object with multiple properties?
  • What would an expression like $..book[(@.length-1)] create?

这篇关于从JSONPath构建JObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆