I am getting api response in json format. Json response structure can be different on every time that's why I want to fetch the value dynamically from Json response.
Json response can be as below(response structure can be different on every time):
{
"userDetails": [{
"firstName": "Howard",
"lastName": "Krispy",
"userId": "1001"
},
{
"firstName": "Leo",
"lastName": "Stenly",
"userId": "1002"
}
]
}
code is as below:
JObject apiResponse= JObject.Parse(result);
string responseKey1 = @"apiResponse[""userDetails""][0][""userId""].ToString()";
var result = responseKey1; //It's giving result "apiResponse[userDetails][0][userId]"
I want to fetch the value from the json response. As I mentioned above result should contain "1001" instead of "apiResponse[userDetails][0][userId]". I have spent couple of days to find the solution but didn't get any proper solution for achieve the result.
So how can I achieve this result?
CodePudding user response:
You've said that you're storing this string in a database (or some external source)
apiResponse[""userDetails""][0][""userId""].ToString()
That's a bad idea, because that's C# code, and you certainly don't want to execute C# code that you load in from an external source.
At a minimum, store a path to the data you want, such as JSONPath, which is better suited for something like this.
string path = "$.userDetails[0].userId";
var userId = apiResponse.SelectToken(path).Value<string>();
// userId is 1001
$.userDetails[0].userId
is safe to put in your database, because it's not code that you execute.
Granted it would be better to normalize all the data you receive and parse so you don't need to guess where the data is.