Here is json object as follows:
string jsonString = "{"name":"John","age":30,"city":"New York"}";
I need to know whether it existence of "age"
or not.
Please give me ur hand.
I tried a lot, but I couldn’t get I expected.
I have to know whether "age"
value is existed on jsonString
or not.
2
Answers
Here's a C# code snippet to check if a key exists in a JSON object string using JSON.NET:
To check the existence of a specific key in a JSON object string using C#, you can use the Newtonsoft.Json library (also known as Json.NET), which is a popular JSON parsing library in the .NET ecosystem. Here’s how you can do it:
First, make sure you have the Newtonsoft.Json library installed in your project. You can install it using NuGet Package Manager or by adding a reference to the Newtonsoft.Json.dll assembly.
Import the necessary namespace in your C# code:
Parse the JSON string into a JObject or JToken using JToken.Parse() or JObject.Parse(). Here’s an example with JObject:
Check if the key exists in the JSON object using the .ContainsKey() method: