Reputation:
In my app, I am posting json string to the server in this manner:
string url = "my/url";
HttpClient newClient = new HttpClient();
string contentType = "application/json";
JObject json = new JObject
{
{ "id", "id" },
{ "apiKey", "apiKey" },
{ "EncryptedData", Data }
};
var jon = JsonConvert.SerializeObject(json);
var content = new StringContent(jon, Encoding.UTF8, contentType);
var TaskPostAsync = await newClient.PostAsync(url, content);
if (TaskPostAsync.IsSuccessStatusCode)
{
var contentString = await TaskPostAsync.Content.ReadAsStringAsync();}
The response I am getting is that it is not in a Json format. Where am I going wrong. Any help would be much appreciated. Data is a string.
Upvotes: 2
Views: 381
Reputation: 247153
By calling
var jon = JsonConvert.SerializeObject(json);
You are serializing it twice.
JObject
is already JSON so all you need to do is call .ToString
to get the JSON
//...
JObject json = new JObject
{
{ "id", "id" },
{ "apiKey", "apiKey" },
{ "EncryptedData", Data }
};
var content = new StringContent(json.ToString(), Encoding.UTF8, contentType);
//...
Reference Write JSON text with JToken.ToString
Another option would be to use an anonymous object and then serialize that
//...
var model = new {
id = "id",
apiKey = "apiKey",
encryptedData = Data
};
var json = JsonConvert.SerializeObject(model);
var content = new StringContent(json, Encoding.UTF8, contentType);
//...
Upvotes: 1