开发者

RESTful API: How to model JSON representation?

开发者 https://www.devze.com 2022-12-28 19:59 出处:网络
I am designing a RESTful API for a booking application. You can request a list of accommodations. And that\'s where I don\'t really know how to design the JSON represenation. This is my XML representa

I am designing a RESTful API for a booking application. You can request a list of accommodations. And that's where I don't really know how to design the JSON represenation. This is my XML representation:

<?xml version="1.0" encoding="utf-8"?>
<accommodations>
    <accommodation>
        <name>...</name>
        <category>couch</category>
    </accommodation>
    <accommodation>
        <name>...</name>
        <category>room</category>
    </accommodation>
<accommodations>

My first try to convert this to JSON resulted in this output (1):

{
    "0": {
        "na开发者_如何学运维me": "...",
        "category": "couch"
    },
    "1": {
        "name": "...",
        "category": "room"
    }
}

But as I looked how others APIs did it, I found something looking more like this (2):

[
    {
        "name": "...",
        "category": "couch" 
    },
    {
        "name": "...",
        "category": "room" 
    }
]

I know version 1 is an object, and version 2 an array.

But which one is better in this case?


You could model the JSON as follows:

{
  "accomodations" : [
    {
      "accomodation" : {
        "name": "...",
        "category": "couch",
        "uri": "http://example.org/accomodations/accomodation_1"
      }
    },
    {
      "accomodation": {
        "name": "...",
        "category": "room",
        "uri": "http://example.org/accomodations/accomodation_2"
      }
    }
  ]
}

and you could return this on a GET http://example.org/accomodations Creating a new accomodation could then be done through a POST http://example.org/accomodations with something like the following in the body:

{
  "accomodation": {
    "name": "...",
    "category": "room"
  }
}


If you are going to use the key (1, 2, ...) as the identifier in communications back to the server the dictionary is better, otherwise I'd go for the array. The unique id then is probably a field in an entry.


Stick with number 2.

Don't model your JSON output after your XML version.

Every major API out there uses representations with Arrays. Most parsing libraries will return List-like instances that make it very easy to manipulate all the objects they contain.

Number 1 is valid JSON but, it's not what the vast majority of your developers will be expecting.

0

精彩评论

暂无评论...
验证码 换一张
取 消