0

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

user2155362
  • 1,657
  • 5
  • 18
  • 30

2 Answers2

2

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"

Milind Thakkar
  • 980
  • 2
  • 13
  • 20
2

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);
  }
}
Ashok Patel
  • 120
  • 8