简体   繁体   中英

What is the proper format for a JSON Response?

I've worked with several different APIs where I needed to parse JSON. And in all cases the Response is constructed a bit differently.

I now need to expose some data via a JSON API and want to know the proper way to deliver that Response.

Here is an example of what I have now, however some users (one using Java) are having difficulty parsing.

    {"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"
      }
    }

The Java user in particular is complaining that they get the error:

org.json.JSONException:[json string] of type org.json.JSONObject cannot be converted to JSONArray

But in Python I am able to take in this Response, fetch "result" and then parse as I would any other JSON data.

* UPDATE *

I passed both my JSON and Twitter's timeline JSON to JSONLint. Both are valid. The Java user can parse Twitter's JSON but not mine. What I noticed with Twitter's JSON is that it's encapsulated with brackets [], signifying an array. And the error this user is getting with my JSON is that it cannot be converted to a JSON array. I didn't think I need to encapsulate in brackets.

It looks valid according to http://json.parser.online.fr/ (random json parser). Its in the other code i'd say ;)

How exactly are you generating this response? Are you doing it yourself?

I see you have a dangling comma at the end of the last element in publishers (ie after the value Kaissa Chess & Games ).

I'd recommend using JSONLint to ensure your JSON is valid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM