我有一个对象说:
public class Comment {
public string Id { get; set; }
public string Author { get; set; }
public string Body { get; set; }
}
每当我在身体中有一个单引号(其他的变种永远不会有它们)
以下一行崩溃:
return JObject.Parse("{ 'Result' : 'Sucessfull!', 'Comment' : '" + JsonConvert.SerializeObject(comment) + "' }");
而且我确定它在身体上,因为这只发生在我做这样的事情时:
comment.Body = "testing th's ";
和其他值是动态设置的,适用于没有单引号的实体。 任何线索为什么会发生这种情况?
注意:如果相关,我需要升级comment.Body
以支持新行
答案 0 :(得分:2)
为什么要将comment
对象作为纯文本添加到JSON中?你试图解析的是这个字符串:
{ 'Result' : 'Sucessfull!', 'Comment' : '{"Id":null,"Author":null,"Body":"testin
g th's"}' }
显然,它不是有效的JSON字符串。您所要做的就是稍微重写一下代码:
return JObject.Parse("{ 'Result' : 'Sucessfull!', 'Comment' : " + JsonConvert.SerializeObject(comment) + " }");
答案 1 :(得分:1)
试试这个
Comment comment = new Comment()
{
Body = "testing th's ",
Author = "Author",
Id = "007"
};
var result = new
{
Result = "Sucessfull!",
Comment = comment
};
return JsonConvert.SerializeObject(result);