0

所以我读到你在请求 json 时不能期望默认顺序。我已经看到这个调用我构建的一个小 api 的实际操作,每次我进行不同的调用时,它都会返回一个混乱的、随机的元素顺序。

像ticketfly的api这样的网站(在这里调用它http://www.ticketfly.com/api/events/upcoming.json?venueId=57)如何始终确保返回的json是特定的顺序?

事件 id 总是第一个,等等。

感谢您对情况有所了解。

4

1 回答 1

1

If you are in control of the endpoint API then you can hardcode the order in which you render the properties. Though I have to ask why exactly do you need the JSON properties in a particular order? You will finally be accessing the properties via there property names so the order in which they appear in the JSON should not ideally matter.

EDIT : Since your bosses insist on this (what can one say now?):

You can try and see if any of the following suits your needs:

  1. Try hardcoding the display order in the view's representation. This means you will need to echo/print each property name explicitly in the view script. In PHP it could be something like echo $variable_representing_json["id"]; and so forth. Note that with this approach you needn't change the original JSON representation.
  2. If you want the original JSON representation to be changed then depending on how you are doing the process it varies in difficulty:
    • If it's string concatenation that you are using to represent the json then hard-code the order in which the json properties get concatenated in the string.
    • In some languages the display order of properties is actually a representation of the order in which the properties were defined. In simple words if $var is an empty json representation then you should define $var["id"] = {some_val} first to display it first.
    • If you are using a framework for processing the JSON data it may have its own quirks irrespective of how you define your representation. In such cases you will have to try and see if you can work around the issue or if it gives any helper methods.
于 2012-12-10T05:24:30.990 回答