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

4
  • stackoverflow.com/questions/17038810/… Commented Feb 2, 2016 at 5:03
  • You need to deserialize into Dictionary<string, object>, since members in C# cannot begin with a number. Commented Feb 2, 2016 at 5:10
  • You r converting to json double times, show us the code where u r converting to json Commented Feb 2, 2016 at 5:29
  • Did the answer below help ? Commented Feb 3, 2016 at 5:58

2 Answers 2

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"

Sign up to request clarification or add additional context in comments.

Comments

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);
  }
}

1 Comment

Yes. Both way possible. Linq or Query

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.