0

I have a simple method in which i try to deserialize a string, in most cases this is a valid object in json but I also have cases like this:

private static string DoSomething(string data)
{
    var result = JsonConvert.DeserializeObject(data);
}

If data is a simply string

data = "Healthy"; // JsonConvert.DeserializeObject throws an exception

JsonReaderException: Unexpected character encountered while parsing value: H. Path '', line 0, position 0.

Sas Gabriel
  • 1,544
  • 2
  • 20
  • 27
  • 1
    @haldo it is, it's just not an object. See https://stackoverflow.com/questions/7487869/is-this-simple-string-considered-valid-json, https://stackoverflow.com/questions/39352207/are-booleans-valid-json – CodeCaster Feb 07 '20 at 11:11
  • 2
    Why do you want to deserialize arbitrary JSON? What is your _actual_ question? If it's _"How to detect whether a string contains a valid JSON object?"_, then research _that_. – CodeCaster Feb 07 '20 at 11:13
  • I implemented a wraper over all my responses so that my api will always return something like {"data" : "value returned by a controller"}, without this the value would be only "value returned by a controller", fast forward a method is only returning a string "Healthy" (for example) – Sas Gabriel Feb 07 '20 at 11:17

0 Answers0