-3

I am writing Unit-Tests and am trying to extract a value from a HttpResponseMessage. I am trying to get the value resultCount. Currenly my string looks like this:"{"resultCount":5,"works":null,"success::false,"errors"null}"

Any ideas how I can get to the 'resultCount:5'

jward01
  • 750
  • 4
  • 11
  • 26
  • 1
    What have you tried so far? Can you please provide some code to make it easier for us to help you? – Joakim Skoog Jan 27 '16 at 17:34
  • Possible duplicate of http://stackoverflow.com/questions/9010021/get-value-from-json-with-json-net – vendettamit Jan 27 '16 at 17:35
  • If you'd be asking for just JSON case that would be duplicate, but since there is no restrictions on format of output it is way too broad for SO. – Alexei Levenkov Jan 27 '16 at 17:36
  • 1
    If one colon in `sucess::false` was after the `"errors"`, this would be well-formed JSON, then you process it easily with a libary like `Newtonsoft.Json`. Where does this string come from? A web service? – Maximilian Gerhardt Jan 27 '16 at 17:36
  • @vendettamit to me OP does not ask for just JSON (you assume OP did not do any research before asking the question - not nice :) ). – Alexei Levenkov Jan 27 '16 at 17:37
  • @AlexeiLevenkov Given the fact that no attempts at solving it have been provided, it can (somewhat) be safely assumed that no research was done either. OP has 25 questions under his belt, so he should know the routine by now. – krillgar Jan 27 '16 at 17:40

2 Answers2

0

Add a reference to your project to "System.Web.Extensions.dll". Then Try:

var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<Dictionary<string, string>>("{'resultCount':5,'works':null,'success':false,'errors' : null}");

Console.WriteLine(dict["resultCount"]);

You will need use using System.Web.Script.Serialization;

-2

I solved it by doing:

     string resultString = resultString = Regex.Match(resultContent, @"\d+").Value;
        int count = Convert.ToInt32(resultString, 10);
        Assert.AreEqual(5, count);

The above method searches the string for any integers and then parses those values to a string. Then I convert the string to an int, and assert the test.

jward01
  • 750
  • 4
  • 11
  • 26
  • What do you do then if the string looks like `{"differentData" :5,"resultCount":1337,"works":null,success:false,"errors":null}`. Just matching the first digits you see in the string checking them to be `10` isn't really fail-proof. – Maximilian Gerhardt Jan 27 '16 at 17:44
  • While it may solve problem for you, this is very bad suggestion in general - please make sure to add alternatives or at least drawbacks of this approach. Also do not add "thank you" notes to questions/answers. – Alexei Levenkov Jan 27 '16 at 17:45