添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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!

One of the points of WebAPI is that you don't need to think about serialization in your action method. Change this to return List<Template> and let WebAPI handle serializing the correct response. You can configure it to return XML, JSON, ...according to the request. – Ian Mercer Nov 10, 2014 at 1:10 In the start, I let WEBAPI handle serialization - even though requirements changed and now I am in the need of HttpResponseMessages. Giving it a try though just resulted in the same error, following a tut on CodeProject. Here is a Screenshot of the returnvalue: i.imgur.com/q6RlbqO.png – user1021605 Nov 10, 2014 at 1:17 Have you tried using the formatting parameter of JsonConvert.SerializeObject() and setting it to Formatting.None? – Brian Rogers Nov 10, 2014 at 7:01

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);
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.