For a .NET Core project, I'm consuming a public API that returns data formatted as JSON. However, some (not all) of their responses have a BOM character at the start of the string, which causes Visual Studio and Json.NET to not recognize the string as valid JSON. As a result, I get an error when using JsonConvert.DeserializeObject() to deserialize the string into my POCO object. I've been told by the API developers that the BOM is included by design, and that I should "set Json.Net to expect that". Is there a way to set Json.NET to handle the BOM without stripping it off the string manually?
Example follows, by request. You can see when the API GET completes successfully, I'm having to trim the BOM manually from the start of the string, otherwise the call to DeserializeObject() fails because the string is not valid JSON.
private static MyPOCO GetObjectFromApi(string url)
{
MyPOCO poco = new MyPOCO();
RestClient client = new RestClient(url);
RestRequest request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
if (response.IsSuccessful)
{
poco = JsonConvert.DeserializeObject<MyPOCO>(response.Content.TrimStart((char)65279)); // trim the byte order marker character at the start of the string
//poco = JsonConvert.DeserializeObject<MyPOCO>(response.Content); // this would throw an error because response.Content is not valid JSON
}
else
{
MyLogger.WriteLog("Api returned failure response");
}
return poco;
}