2011-02-24 70 views
1

我已經與幾個不同的API合作,我需要解析JSON。在所有情況下,Response的構造都有所不同。什麼是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字符串]類型org.json.JSONObject的不能轉換到JSONArray

但在Python中,我能夠接受此響應,獲取「結果」,然後像解析其他任何JSON數據一樣解析。

* UPDATE *

我通過我的JSON和Twitter的時間表JSON來JSONLint兩者。兩者都是有效的。 Java用戶可以解析Twitter的JSON,但不是我的。我用Twitter的JSON注意到的是它用括號[]括起來,表示一個數組。而且這個用戶用我的JSON獲得的錯誤是它不能被轉換成JSON數組。我不認爲我需要將其封裝在括號內。

+1

THat錯誤意味着他們正試圖將其轉換爲數組,而它不是一個?你可以在得到這個錯誤時顯示他們在做什麼嗎? – Nanne 2011-02-24 15:49:07

+0

好問題 - 會得到答案。但是你沒有看到這個Response格式正確的錯誤?我注意到Twitter將它們的響應格式化爲[{key:value,key,value}]。注意封裝托架。這位用戶說他解析Twitter的JSON沒有問題。 – 2011-02-24 15:53:34

+1

如果你看[JSON頁面](http://www.json.org/),一個數組被定義爲'[elements]'',其中'elements'可以是'object'(這就是你的例子) Twitter節目)或'string | number | array | true | false | null「這就是你的JSON響應示例顯示的內容。我同意@Nanne,你需要檢查你的用戶,看看他在做什麼,因爲你的JSON似乎是有效的,所以你的用戶沒有正確使用它。 – 2011-02-24 16:00:25

回答

1

它看起來依據http://json.parser.online.fr/(隨機json解析器)有效。它在我說的其他代碼;)

+0

我已經把它放回另一個法庭。我相信用戶通過使用JSONArray解析不正確。 – 2011-02-24 17:48:09

0

您究竟如何產生這種響應?你自己在做嗎?

我看到你在publishers(即在值Kaissa Chess & Games之後)的最後一個元素的末尾有一個搖晃的逗號。

我建議使用JSONLint以確保您的JSON有效。

+0

好眼睛。這是一個剪切和粘貼錯誤 - 修復。 – 2011-02-24 15:51:44

相關問題