From C# I'm calling RESTful web service that returns JSON. The service can return an arbitrary Javascript object, we don't know its structure at compile time.
Usually, it returns a JSON object, but there are situations where it returns a simple string. JSON.Net throws a runtime error when I try to deserialize the simple string.
dynamic dyn = JsonConvert.DeserializeObject("just a string");
throws:
Newtonsoft.Json.JsonReaderException was unhandled by user code
HResult=-2146233088
Message=Unexpected character encountered while parsing value: j. Path '', line 0, position 0.
I read the answers to Is this simple string considered valid JSON? and the consensus seems to be that returning a simple string as JSON is legal, but many implementations don't yet support this.
Is this true for JSON.NET? What are the workarounds to handle deserializing JSON that might contain simple types and not just objects and arrays?
This seems to work fine, am I missing something?
dynamic dyn;
dyn = GetObjectFromJSON("{ \"name\": \"john\", \"age\": 32 }");
Debug.WriteLine((string)Convert.ToString(dyn));
dyn = GetObjectFromJSON("[ \"a\", \"b\", \"c\" ]");
Debug.WriteLine((string)Convert.ToString(dyn));
dyn = GetObjectFromJSON("just a string");
Debug.WriteLine((string)Convert.ToString(dyn));
dyn = GetObjectFromJSON("35");
Debug.WriteLine((string)Convert.ToString(dyn));
dyn = GetObjectFromJSON("true");
Debug.WriteLine((string)Convert.ToString(dyn));
dyn = GetObjectFromJSON(null);
Debug.WriteLine((Object)dyn ?? "(null)");
and
private Object GetObjectFromJSON(string jsonString)
{
if (String.IsNullOrEmpty(jsonString))
{
return null;
}
dynamic jsonResponse;
jsonString = jsonString.Trim();
if (jsonString.StartsWith("{") || jsonString.StartsWith("["))
{
// object or array
jsonResponse = JsonConvert.DeserializeObject(jsonString);
}
else
{
// some literal value
double d;
bool b;
if (Double.TryParse(jsonString, out d))
{
return d;
}
else if (bool.TryParse(jsonString, out b))
{
return b;
}
else
{
// not null, not an object, not an array, not a number, and not a boolean, so it's a string
jsonResponse = jsonString;
}
}
return jsonResponse;
}