I issue a request to an API, and I'm able to parse the success response result (response.Content.ReadAsStringAsync().Result)
, but when I get a failure response ("bad request"), the seemingly well-formed JSON result cannot be parsed by JObject.Parse()
or JToken.Parse()
, they throw.
using System;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
var result = "\"{\\\"error\\\":{\\\"detail\\\":\\\"java.lang.NullPointerException\\\",\\\"message\\\":\\\"Error occured while setting field 'caller_id' with value null\\\"},\\\"status\\\":\\\"failure\\\"}\"";
var jObject = JObject.Parse(result);
Console.WriteLine(jObject["error"]["message"]);
}
}
The exception:
Run-time exception (line 10): Error reading JObject from JsonReader. Current JsonReader item is not an object: String. Path '', line 1, position 162.
Stack Trace:
[Newtonsoft.Json.JsonReaderException: Error reading JObject from JsonReader. Current JsonReader item is not an object: String. Path '', line 1, position 162.] at Newtonsoft.Json.Linq.JObject.Load(JsonReader reader, JsonLoadSettings settings) at Newtonsoft.Json.Linq.JObject.Parse(String json, JsonLoadSettings settings) at Newtonsoft.Json.Linq.JObject.Parse(String json) at Program.Main() :line 10
The exception points to the very end of the string, but I can't figure out what's missing. https://jsonblob.com can parse it after I remove the backslashes, I got rid of the apostrophe's, I "cleaned it up" with string and regex replace, I turned into a char array and build it again, all to no avail.
Help appreciated!
var result = "{\"error\":{\"detail\":\"java.lang.NullPointerException\",\"message\":\"Error occured while setting field 'caller_id' with value null\"},\"status\":\"failure\"}";
successfully. – yW0K5o