gpt4 book ai didi

c# - 单引号时 JsonConvert.SerializeObject 失败

转载 作者:行者123 更新时间:2023-11-30 21:58:35 33 4
gpt4 key购买 nike

我有一个对象说:

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) + "' }");

而且我确定它在 body 上,因为只有当我做这样的事情时才会发生这种情况:

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) + " }");

关于c# - 单引号时 JsonConvert.SerializeObject 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29961928/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com