so currently I am working on a WebAPI and I run in the following error.
While I try to return a List serialized with JsonConvert.SerializeObject(object) my second attribute (string JSON) get covered up by carriage returns and line feeds.
Here is the code:
public class Template
{
public string Name;
public string JSON;
}
public HttpResponseMessage GetAll()
{
var items = db.GetTemplates().ToList<Template>();
var resp = new HttpResponseMessage()
{
Content = new StringContent(JsonConvert.SerializeObject(items),Encoding.UTF8,"application/json")
};
resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return resp;
}
Changing to:
Content = new StringContent(JsonConvert.SerializeObject(items.ToList<Template>()[0]),Encoding.UTF8,"application/json")
Shows the same error
While changing the code to:
Content = new StringContent(JsonConvert.SerializeObject(items.ToList<Template>()[0].JSON),Encoding.UTF8,"application/json")
Everything returns fine...
Checked in Browser, not in Visual Studio!
Anyone got a hint for me? Google just won't let me find the answer.
Thanks in Advance!
As mentioned in a comment by Brian Rogers, Use JsonSerializerSettings Formatting = Formatting.None property:
JsonSerializerSettings jsonSettings = new JsonSerializerSettings
{
Formatting = Formatting.None
};
string jsonString = JsonConvert.SerializeObject(items,jsonSettings);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With