![](/img/trans.png)
[英]Error for enumerable when using JsonConvert.SerializeObject
[英]JsonConvert.SerializeObject failes when having a single quote
我有一個對象說:
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 ";
和其他值是動態設置的,適用於不帶單引號的主體。 任何線索為什么會這樣?
注意:我需要升級comment.Body
以便以后支持新行
為什么將comment
對象作為純文本添加到JSON? 您嘗試解析的是以下字符串:
{ 'Result' : 'Sucessfull!', 'Comment' : '{"Id":null,"Author":null,"Body":"testin
g th's"}' }
顯然,它不是有效的JSON字符串。 您要做的就是稍微重寫一下代碼:
return JObject.Parse("{ 'Result' : 'Sucessfull!', 'Comment' : " + JsonConvert.SerializeObject(comment) + " }");
嘗試這個
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.