Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
722 views
in Technique[技术] by (71.8m points)

c# - Build JObject from JSONPath

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?

So for example something like the following.

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

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

{
    "ArrayA": [{
        "ArrayB": [{
            "Property": ""
        }]
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No.

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"

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", ""))))))));

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:

  • 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?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...