[英]Can't write JSON string in Groovy/Java
因此,我尝试将以下JSON编写为Java字符串,但遇到我不理解的错误:
String simpleAPI_MessageInJSON = "{ " +
" \"action\": \"add\", " +
" \"destinations\": { " +
" \"cache\": 1, " +
" \"batches\": 1 " +
" }, " +
" \"payload\": { " +
" \"object_type\": \"profile\", " +
" \"object_id\": 366334, " +
" } " +
" } ";
错误:
com.fasterxml.jackson.core.JsonParseException:意外的字符('}'(代码125)):期望双引号开头字段名称
您还有一个逗号:
" \"object_id\": 366334, " +
应该:
" \"object_id\": 366334 " +
// /\ Extra comma was there.
错误消息显示:
com.fasterxml.jackson.core.JsonParseException:意外的字符('}'(代码125)):期望双引号开头字段名称
这不是很清楚,但是我们可以确定这是某种语法错误,并且具有行号。 通过查看行号,可以发现语法错误。
如果使用groovy来提高可读性,通常使用多行字符串会更容易:
String simpleAPI_MessageInJSON = '''{
| "action": "add",
| "destinations": {
| "cache": 1,
| "batches": 1
| },
| "payload": {
| "object_type": "profile",
| "object_id": 366334
| }
|}'''.stripMargin()
@Annubian Noob
奇怪,适用于常规
import groovy.json.JsonSlurper
String simpleAPI_MessageInJSON = "{ " +
" \"action\": \"add\", " +
" \"destinations\": { " +
" \"cache\": 1, " +
" \"batches\": 1 " +
" }, " +
" \"payload\": { " +
" \"object_type\": \"profile\", " +
" \"object_id\": 366334, " +
" } " +
" } "
def parsed = new JsonSlurper().parseText(simpleAPI_MessageInJSON)
assert parsed.action == "add"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.