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.

Matt W
  • 11,753
  • 25
  • 118
  • 215
  • Maybe this has the answer you need: [Deserialize JSON into C# dynamic object?](https://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object) – Catalin Aug 07 '19 at 12:19
  • 1
    Have you considered JSON queries using JSONPath etc? There's a tool here that uses those technologies http://www.jsonquerytool.com/ (JSONPath is built into JSON.Net - https://www.newtonsoft.com/json/help/html/QueryJsonSelectTokenJsonPath.htm) – Charleh Aug 07 '19 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. – Matt W Aug 07 '19 at 12:27
  • @charleh Thank you - I had forgotten about that class. :) Would you like to post an answer so I can accept it? – Matt W Aug 07 '19 at 12:38

1 Answers1

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

Charleh
  • 13,749
  • 3
  • 37
  • 57