Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonConvert.SerializeObject adds \r\n

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!

like image 990
user1021605 Avatar asked Jul 05 '26 13:07

user1021605


1 Answers

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);
like image 129
Darrel K. Avatar answered Jul 07 '26 09:07

Darrel K.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!