'c# httpclient unable to read post response as json
I can't get my dotnet web api (v. 5.0) to read the json response from another API. It insists on 'decorating' the string with \ and removing quotes. I suspect it assumes the returned content is in a certain format and then tries to 'deserialize' the json content into a string.
My API returns this
{
"result": [
{
"CampaignId": 1
}
]
}
According to postman, the returned raw data is {"result":[{"CampaignId":1}]}
Which seems reasonable.
Problem is, responseContent in the following code
var bodyStr = body.ToString();
var client = new HttpClient();
var httpContent = new StringContent(bodyStr, Encoding.UTF8, "application/json");
var response = await client.PostAsync("http://anotherapi/query",httpContent);
var responseContent = await response.Content.ReadAsStringAsync();
returns
"{\"result\":[{CampaignId:1}]}"
which obviously fails when reading it as json
using (JsonDocument document = JsonDocument.Parse(responseContent)) {}
EDIT:
I get the following exception, when calling JsonDocument.Parse(responseContent):
System.Text.Json.JsonReaderException: 'C' is an invalid start of a property name. Expected a '"'. LineNumber: 0 | BytePositionInLine: 12.
because ReadAsStringAsync() seems to remove the quotes around "CampaignId", which makes the json invalid.
EDIT2: This is the returned response from the other API, according to postman:

This is the response according to curl:
$ curl --data "@/somedata.txt" -X POST -H "Content-Type: application/json" http://host/query
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 19847 100 30 100 19817 30 19817 0:00:01 0:00:01 --:--:-- 16083{"result":[{"CampaignId":1}]}
I don't see any problems with the response header or content. Everything seems fine with the returned content and "campaignId" includes the quotes.
Solution 1:[1]
The mormot API that was returning the response, didn't add quotes around campaignId, because it used its own extended JSON format.
It used the extended JSON format, because the User Agent wasn't set in the request header.
Adding a default header to my httpclient, made it work:
var client = new HttpClient();
var productValue = new ProductInfoHeaderValue("A Header", "1.0");
var commentValue = new ProductInfoHeaderValue("(a comment)");
client.DefaultRequestHeaders.UserAgent.Add(productValue);
client.DefaultRequestHeaders.UserAgent.Add(commentValue);
Solution 2:[2]
You can try to add to your HttpClient this header, maybe it can help
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
But I highly recommend you to use Newtonsoft.Json. Any another serialiazers are only good for serializing "Hello World!" . Using Newtonsoft.Json I could parse your json without any problem
using Newtonsoft.Json;
var json="{\"result\":[{CampaignId:1}]}";
var jsonObject= JObject.Parse(json);
if you want to fix your json, just convert parsed object to json again
json=jsonObject.ToString();
result
{
"result": [
{
"CampaignId": 1
}
]
}
now you can use any serializer you like. If you are using net API, maybe it is better if you show us your APi code, and your startup code too. We could help you to assign another serializer to Api controller and it will return json in a right format.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user1538142 |
| Solution 2 |

