In a Web API controller, I return a JSON encoded object, in fact a list of Organization
objects, each with its own collection of Branch
objects, again each with a list of Person
objects.
I return it like this from the controller, as an IHttpActionResult
:
return Ok(SerializeObject(orgs));
where:
protected virtual string SerializeObject(object source)
{
return JsonConvert.SerializeObject(source, SharedSettings.JsonSerializerSettings);
}
and
public static JsonSerializerSettings JsonSerializerSettings { get; } = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
StringEscapeHandling = StringEscapeHandling.EscapeNonAscii,
TypeNameHandling = TypeNameHandling.None,
NullValueHandling = NullValueHandling.Include
};
I request it like:
HttpResponseMessage response = await Client.PostAsync(resource, null);
if (!response.IsSuccessStatusCode)
{
RaiseException(response, exMsg);
}
var content = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<TReturn>(content, SharedSettings.JsonSerializerSettings);
I don't use response.Content.ReadAsAsync<TReturn>()
because I want to be really sure I'm using the same Json serializer and its settings on both sides. The JSON returned looks fine, if you'll excuse a few lines for brevity:
[
{
"Branches": [
{
"People": [
{
"FullName": "Katie Darwin",
"BranchId": 2,
"OrgId": 2,
"Id": 18
}
],
"Name": "Jolimont",
"Phone": null,
"OrgId": 2,
"Id": 2
}
],
"Name": "Contoso, Ltd.",
"Id": 2
},
{
"Branches": [],
"Name": "Trey Research",
"Id": 11
}
]
The exception I get on deserialisation is
'Error converting value "" " to type 'System.Collections.Generic.List`1[ApptEase.DataModels.Entities.Organization]'. Path '', line 1, position 439200.
I have never experienced any such trouble with NewtonSoft JSON before, but maybe I'm only placed less demand on it. Does anyone have any idea what could be wrong?
BREAKING: If I write that JSON string to a file, then read it with a small test program, it deserialises fine, with no explicit options. Being hopeful, I removed the options clause from the deserialize in the main program, but I still get the same error. I think I should start looking at a text encoding problem.
It might also be noted that the Content-Length
header and the error position are equal: 439200.