[英]Can't write JSON string in Groovy/Java
So I am trying to write the following JSON as a Java string but getting an error I don't understand: 因此,我尝试将以下JSON编写为Java字符串,但遇到我不理解的错误:
String simpleAPI_MessageInJSON = "{ " +
" \"action\": \"add\", " +
" \"destinations\": { " +
" \"cache\": 1, " +
" \"batches\": 1 " +
" }, " +
" \"payload\": { " +
" \"object_type\": \"profile\", " +
" \"object_id\": 366334, " +
" } " +
" } ";
ERROR: 错误:
com.fasterxml.jackson.core.JsonParseException: Unexpected character ('}' (code 125)): was expecting double-quote to start field name
com.fasterxml.jackson.core.JsonParseException:意外的字符('}'(代码125)):期望双引号开头字段名称
You have an extra comma: 您还有一个逗号:
" \"object_id\": 366334, " +
Should be: 应该:
" \"object_id\": 366334 " +
// /\ Extra comma was there.
The error message says: 错误消息显示:
com.fasterxml.jackson.core.JsonParseException: Unexpected character ('}' (code 125)): was expecting double-quote to start field name
com.fasterxml.jackson.core.JsonParseException:意外的字符('}'(代码125)):期望双引号开头字段名称
This isn't very clear, but we can make out that it's a syntax error of some kind, and it has a line number. 这不是很清楚,但是我们可以确定这是某种语法错误,并且具有行号。 By looking around the line number, you can find the syntax error.
通过查看行号,可以发现语法错误。
It's generally easier to use multi-line strings if you are using groovy for improved readability: 如果使用groovy来提高可读性,通常使用多行字符串会更容易:
String simpleAPI_MessageInJSON = '''{
| "action": "add",
| "destinations": {
| "cache": 1,
| "batches": 1
| },
| "payload": {
| "object_type": "profile",
| "object_id": 366334
| }
|}'''.stripMargin()
@Annubian Noob @Annubian Noob
Strange, works with groovy: 奇怪,适用于常规
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.