0

I wish to write some C# which allows the client to provide a JSON string and query string. The query string would then be used to address values in the JSON object.

For example, if I had this JSON:

{
  "head": "big",
  "fingers": [
    "one", "thumb",
    "two", "ring"
  ],
  "arm": {
    "elbow", "locked"
  }
}

And this query string:

"fingers.two"

I would want to return the value "ring".

Is this (or something like it) possible in C#?

I have tried using the ExpandoObject class, but this does not allow dynamic runtime inspection:

var json = JsonConvert.DeserializeObject<ExpandoObject>(jsonStr);

As far as I can tell, the discovery of values on the json variable needs to be done at code time, rather than runtime, which means I cannot dynamically find values being queried for.

4
  • Maybe this has the answer you need: Deserialize JSON into C# dynamic object? Commented Aug 7, 2019 at 12:19
  • 1
    Have you considered JSON queries using JSONPath etc? There's a tool here that uses those technologies jsonquerytool.com (JSONPath is built into JSON.Net - newtonsoft.com/json/help/html/QueryJsonSelectTokenJsonPath.htm) Commented Aug 7, 2019 at 12:23
  • @catalin I don't think so because I want to specify the value to be retrieved as a string, rather than code. Commented Aug 7, 2019 at 12:27
  • @charleh Thank you - I had forgotten about that class. :) Would you like to post an answer so I can accept it? Commented Aug 7, 2019 at 12:38

1 Answer 1

1

JSONPath does this

Assuming the following JSON (fixed a few syntax errors in the original)

{
  "head": "big",
  "fingers": {
    "one":"thumb",
    "two":"ring"
  },
  "arm": {
    "elbow": "locked"
  }
}

And this query

MyJObjectOrToken.SelectToken("fingers.two")

You will get the following output:

[
    "ring"
]

It should be trivial then to extract the value as a string using JSON.Net methods and return the result to your user.

Support for JSONPath is built into JSON.Net

https://www.newtonsoft.com/json/help/html/SelectToken.htm

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.