C# JsonConvert.SerializeObject在具有单个引号时失败
我的目标是:C# JsonConvert.SerializeObject在具有单个引号时失败,c#,asp.net,json,C#,Asp.net,Json,我的目标是: public class Comment { public string Id { get; set; } public string Author { get; set; } public string Body { get; set; } } 每当我在正文中有一句话时(其他VAR将永远不会有) 以下线路发生故障: return JObject.Parse("{ 'Result' : 'Sucessfull!', 'Comment' : '" + Jso
public class Comment {
public string Id { get; set; }
public string Author { get; set; }
public string Body { get; set; }
}
每当我在正文中有一句话时(其他VAR将永远不会有)
以下线路发生故障:
return JObject.Parse("{ 'Result' : 'Sucessfull!', 'Comment' : '" + JsonConvert.SerializeObject(comment) + "' }");
我确信它在身体上,因为只有当我这样做的时候才会发生:
comment.Body = "testing th's ";
其他值是动态设置的,适用于没有单引号的实体。
你知道为什么会这样吗
注意:如果相关的话,我需要升级注释.Body以支持后面的新行
Comment comment = new Comment()
{
Body = "testing th's ",
Author = "Author",
Id = "007"
};
var result = new
{
Result = "Sucessfull!",
Comment = comment
};
return JsonConvert.SerializeObject(result);
为什么要将
注释对象作为纯文本添加到JSON中?您尝试分析的是以下字符串:
{ 'Result' : 'Sucessfull!', 'Comment' : '{"Id":null,"Author":null,"Body":"testin
g th's"}' }
显然,它不是有效的JSON字符串。您所要做的就是稍微重写代码:
return JObject.Parse("{ 'Result' : 'Sucessfull!', 'Comment' : " + JsonConvert.SerializeObject(comment) + " }");