skip to Main Content

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


  1. Chosen as BEST ANSWER

    Here's a C# code snippet to check if a key exists in a JSON object string using JSON.NET:

    using Newtonsoft.Json.Linq;
    
    class Program
    {
        static void Main(string[] args)
        {
            // Your JSON object string
            string jsonString = "{"name":"John","age":30,"city":"New York"}";
    
            // Parse the JSON string into a JObject
            JObject jsonObj = JObject.Parse(jsonString);
    
            // Key to check for existence
            string keyToCheck = "age";
    
            // Check if the key exists in the JSON object
            bool keyExists = jsonObj.ContainsKey(keyToCheck);
    
            // Output the result
            if (keyExists)
            {
                Console.WriteLine($"The key '{keyToCheck}' exists in the JSON object.");
            }
            else
            {
                Console.WriteLine($"The key '{keyToCheck}' does not exist in the JSON object.");
            }
        }
    }
    

  2. 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:

    using Newtonsoft.Json.Linq;
    

    Parse the JSON string into a JObject or JToken using JToken.Parse() or JObject.Parse(). Here’s an example with JObject:

    string jsonString = "{"key1": "value1", "key2": "value2", "key3": 
    "value3"}";
    JObject jsonObject = JObject.Parse(jsonString);
    

    Check if the key exists in the JSON object using the .ContainsKey() method:

    string keyToCheck = "key2";
    
    if (jsonObject.ContainsKey(keyToCheck))
    {
        Console.WriteLine($"The key '{keyToCheck}' exists in the JSON 
        object.");
    }
    else
    {
        Console.WriteLine($"The key '{keyToCheck}' does not exist in the JSON 
        object.");
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search