System.JSONException:意外字符('i'(代码 105)):需要逗号分隔 [行:1,列:18] 处的 OBJECT 条目

问题描述 投票:0回答:1

#Salesforce挑战

我正在尝试转义字符串,但到目前为止还没有成功。

这是我收到的响应正文:

{"text":"this \"is something\" I wrote"}

请注意,有 2 个反斜杠来转义双引号字符。 (这是一个示例。实际上,我有很多“文本”元素需要逃避。) 当我尝试反序列化它时,出现以下错误:

System.JSONException: Unexpected character ('i' (code 105)): was expecting comma to separate OBJECT entries at [line:1, column:18]

我尝试使用以下方法逃脱:

String my = '{"text":"this \"is something\" I wrote"}';
System.debug('test 0: ' + my);
System.debug('test 1: ' + my.replace('\"', '-'));
System.debug('test 2: ' + my.replace('\\"', '-'));
System.debug('test 3: ' + my.replace('\\\"', '-'));
System.debug('test 4: ' + my.replace('\\\\"', '-'));

--- 结果:

[22]|DEBUG|test 0: {"text":"this "is something" I wrote"}
[23]|DEBUG|test 1: {-text-:-this -is something- I wrote-}
[23]|DEBUG|test 1: {-text-:-this -is something- I wrote-}
[24]|DEBUG|test 2: {"text":"this "is something" I wrote"}
[25]|DEBUG|test 3: {"text":"this "is something" I wrote"}
[26]|DEBUG|test 4: {"text":"this "is something" I wrote"}

--- 我需要的结果:

{"text":"this -is something- I wrote"}

请问有人有任何解决办法可以分享吗?

非常感谢。

string salesforce escaping apex
1个回答
0
投票

这是您在 Anonymous Apex 中运行测试时出现的问题:

String my = '{"text":"this \"is something\" I wrote"}';

因为 \ 是转义字符,所以您需要在 Apex 字符串文字中使用两个反斜杠才能在实际输出中生成反斜杠:

String my = '{"text":"this \\"is something\\" I wrote"}';

由于 Apex 用 ' 引用字符串,因此您不必转义 Apex 的引号;你正在为 JSON 解析器转义它们。

同样的原则适用于您尝试用于替换的字符串:您必须对 Apex 转义 \。


尽管如此,目前还不清楚您为什么要尝试手动更改此字符串。有效负载

{"text":"this \"is something\" I wrote"}

是有效的 JSON。一般来说,您不应该对 Apex 中的入站 JSON 结构执行字符串替换,除非您尝试补偿包含 Apex 保留字作为键的有效负载,以便您可以使用类型化反序列化。

© www.soinside.com 2019 - 2024. All rights reserved.