JSON响应的正确格式是什么?
我之前接触过好几种不同的API,需要处理JSON数据。在这些情况下,返回的数据格式都有点不同。
现在我需要通过一个JSON API来提供一些数据,想知道正确的返回格式应该是什么样的。
下面是我现在的返回格式的一个例子,不过有些用户(其中一个用Java)在解析时遇到了困难。
{"status": "200 OK",
"code": "\/api\/status\/ok",
"result": {
"publishers": ["Asmodee", "HOBBITY.eu", "Kaissa Chess & Games"],
"playing_time": 30, "description": "2010 Spiel des Jahres WinnerOne player is the storyteller for the turn. He looks at the 6 images in his hand. From one of these, he makes up a sentence and says it out loud (without showing the card to the other players).The other players select amongst their 6 images the one that best matches the sentence made up by the storyteller.Then, each of them gives their selected card to the storyteller, without showing it to the others. The storyteller shuffles his card with all the received cards. ",
"expansions": ["Dixit 2", "Dixit 2: \"Gift\" Promo Card", "Dixit 2: The American Promo Card", "Dixit Odyssey"],
"age": 8,
"min_players": 3,
"mid": "\/m\/0cn_gq3",
"max_players": null,
"designers": ["Jean-Louis Roubira"],
"year_published": 2008,
"name": "Dixit"
}
}
特别是那个用Java的用户抱怨说,他们遇到了这个错误:
org.json.JSONException:[json string] 类型的 org.json.JSONObject 不能转换为 JSONArray
但在Python中,我可以接收这个返回,提取“result”部分,然后像处理其他JSON数据一样解析它。
* 更新 *
我把我的JSON和Twitter的时间线JSON都放到JSONLint上检查过,结果都是有效的。那个Java用户可以解析Twitter的JSON,但解析不了我的。我注意到Twitter的JSON是用方括号[]包裹的,这表示它是一个数组。而这个用户在解析我的JSON时遇到的错误是它不能被转换为JSON数组。我原本以为不需要用方括号包裹。
2 个回答
0
你是怎么生成这个回复的?是你自己做的吗?
我注意到你在 publishers
的最后一个元素后面有个多余的逗号(也就是在值 Kaissa Chess & Games
后面)。
我建议你使用 JSONLint 来检查一下你的 JSON 是否有效。
1
根据这个随机的 JSON 解析器 http://json.parser.online.fr/,看起来是有效的。我觉得问题出在其他代码上;)