【发布时间】:2011-02-24 15:45:56
【问题描述】:
我使用过几种不同的 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] of type org.json.JSONObject 无法转换为 JSONArray
但在 Python 中,我可以接收此响应,获取“结果”,然后像解析任何其他 JSON 数据一样进行解析。
* 更新 *
我将我的 JSON 和 Twitter 的时间线 JSON 都传递给了 JSONLint。两者都是有效的。 Java 用户可以解析 Twitter 的 JSON,但不是我的。我注意到 Twitter 的 JSON 是用括号 [] 封装的,表示一个数组。这个用户在使用我的 JSON 时遇到的错误是它无法转换为 JSON 数组。我认为我不需要封装在括号中。
【问题讨论】:
-
该错误意味着他们正在尝试将其转换为数组,而它不是一个?您能否展示他们在收到此错误时正在做什么?
-
好问题 - 将得到答案。但是您看不出这种响应格式有什么问题吗?我注意到 Twitter 将他们的响应格式化为 [{key: value, key, value}]。注意封装括号。这位用户说他解析 Twitter 的 JSON 没有问题。
-
如果您查看JSON page,则数组定义为
[elements],其中elements可以是object(这是您的Twitter 示例所显示的)或string | number |array | true | false | null,其中是您的 JSON 响应示例显示的内容。我同意@Nanne,您需要与您的用户核实一下,看看他在做什么,因为您的 JSON 似乎是有效的,所以是您的用户没有正确使用它。 -
好的,我会跟进更多问题 - 谢谢!
-
还有 no.good.at.coding - 你回答了我对 JSON 如何定义数组的困惑。