Home > Back-end >  Get value of any json by defining a key pattern at runtime
Get value of any json by defining a key pattern at runtime

Time:03-16

I want to extract values of any json which I do not know the structure of at compile time. So I am looking for something like that:

public class JsonExtractor
{
    public string GetValue(string pattern, string json)
    {
        return JsonConvert.GetValue<string>(json, pattern);
    }
}
string pattern = ".data.value";
string json = "{\"request\": {\"method\": \"get\", \"key\": \"test\"}, \"code\": 0, \"type\": \"call\", \"data\": {\"value\": 14.0}}";

var jsonExtractor = new JsonExtractor();
var value = jsonExtractor.GetValue(pattern, json);

What's important here is the value of pattern and the value structure of the json is not known at compile time, i just created these two variables for illustration. I want to get a specific value within any json at runtime.

CodePudding user response:

Use SelectToken and modify your pattern to be a JSONPath (which is just adding a "$" to the start).

string pattern = "$.data.value";
string json = "{\"request\": {\"method\": \"get\", \"key\": \"test\"}, \"code\": 0, \"type\": \"call\", \"data\": {\"value\": 14.0}}";
int data = JToken.Parse(json).SelectToken(pattern).Value<int>();
Console.WriteLine(data); // print "14"

Note that you can put <string> as the generic argument as well, even though the JSON value is a Number.

  • Related