简体   繁体   English

单引号时JsonConvert.SerializeObject失败

[英]JsonConvert.SerializeObject failes when having a single quote

I have an object say: 我有一个对象说:

public class Comment {
    public string Id { get; set; }
    public string Author { get; set; }
    public string Body { get; set; }
}

And whenever I have a single quote in the body (the others vars will never have them) 而且每当我体内有一个单引号时(其他var将永远不会有它们)

the following line crashes: 以下行崩溃:

return JObject.Parse("{ 'Result' : 'Sucessfull!', 'Comment' : '" + JsonConvert.SerializeObject(comment) + "' }");

And I'm sure it's on the body, because this only happens when I do something like this: 而且我确定它在身体上,因为只有当我做这样的事情时才会发生这种情况:

comment.Body = "testing th's ";

and the other values, are dynamicly set, and work for bodies without the single quotes. 和其他值是动态设置的,适用于不带单引号的主体。 any clue why this is happening? 任何线索为什么会这样?

Note: I need to upgrade the comment.Body to support new lines later on if that is relevant 注意:我需要升级comment.Body以便以后支持新行

Why do you add the comment object to your JSON as plain text? 为什么将comment对象作为纯文本添加到JSON? What you try to parse is this string: 您尝试解析的是以下字符串:

{ 'Result' : 'Sucessfull!', 'Comment' : '{"Id":null,"Author":null,"Body":"testin
g th's"}' }

Obviously, it is not a valid JSON string. 显然,它不是有效的JSON字符串。 All you have to do is to rewrite your code a little bit: 您要做的就是稍微重写一下代码:

return JObject.Parse("{ 'Result' : 'Sucessfull!', 'Comment' : " + JsonConvert.SerializeObject(comment) + " }");

Try this 尝试这个

Comment comment = new Comment()
{
    Body = "testing th's ",
    Author = "Author",
    Id = "007"
 };

 var result = new
 {
  Result = "Sucessfull!",
  Comment = comment
 };

 return JsonConvert.SerializeObject(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM