user2155362
user2155362

Reputation: 1703

How can I parse such json string

I receive a json string from webclient such like below:

"{\"1\": \"on\", \"2\": \"on\"}"

Now I should convert it into some struct and fetch the value,the point is the value is not fixed, it may be this:

"{\"1\": \"on\", \"2\": \"on\", \"3\": \"off\"}"

or this

"{\"1\": \"on\", \"2\": \"off\", \"3\": \"on\", \"4\": \"on\"}"

so my question is how can I parse such string. I need to fetch the value which is "on".

Thanks

Upvotes: 0

Views: 54

Answers (2)

Ashok Patel
Ashok Patel

Reputation: 120

Dependency for this is :Newtonsoft.Json,Newtonsoft.Json.Linq; http://www.newtonsoft.com/json

You can use following code to find the value of on.

 //var test = "{\"1\": \"on\", \"2\": \"on\"}";

//var test = "{\"1\": \"on\", \"2\": \"on\", \"3\": \"off\"}";

var test = "{\"1\": \"on\", \"2\": \"off\", \"3\": \"on\", \"4\": \"on\"}";

JObject obj = JObject.Parse(test);

foreach (var pair in obj)
{
  if (obj[pair.Key].ToString() == "on")
  {
    Console.WriteLine(pair.Key);
  }
}

Upvotes: 2

Milind Thakkar
Milind Thakkar

Reputation: 980

You could use JSON.Net (http://www.newtonsoft.com/json ) which is also available to NuGet.

JObject obj = JObject.Parse("{\"1\": \"on\", \"2\": \"on\", \"3\": \"off\"}");
        var val = (string)obj.Descendants()
                   .OfType<JProperty>()
                   .Where(x => x.Value.ToString() == "on")
                   .First().Name;

This will get you first node with value "on"

Upvotes: 2

Related Questions