LukeFilewalker
LukeFilewalker

Reputation: 752

Best Practice Design typed JSON Objects

Currently we are designing a System that will send JSON Objects to registered consumers. The consumers will be able to register for different Object Types that they want to receive. Currently we are designing the JSON Objects that will be consumed by the registered consumers.

As we see there are two possible approaches to define typed JSON Objects.

  1. A generic JSON Object that has some properties set or it has them not set:
{
  "timestamp": 1589448935,
  "customer_id": "123123123123",
  "message": {
    "title": "Desired Title",
    "text": "The Text of the Message",
  }
}
{
  "timestamp": 1589448935,
  "customer_id": "123123123123",
  "message": {
    "title": "Desired Title",
    "text": "The Text of the Message",
    "avatar": "http://avatar.io/avatar"
  }
}
  1. A Type field on each JSON Object that specifies which Type this object is from:
{
  "timestamp": 1589448935,
  "customer_id": "123123123123",
  "type": "simple_message",
  "message": {
    "title": "Title",
    "text": "Message",
  }
}
{
  "timestamp": 1589448935,
  "customer_id": "123123123123",
  "type": "avatar_message",
  "message": {
    "title": "Title",
    "text": "Message",
    "avatar": "http://www.avatar.io/avatar"
  }
}

From our point of view a more generic approach would be easier to handle within our system, because we would not need to handle multiple types, we just can append a property or leave it away.

From point of view of a developer I could imagine that a type field could help the developer when handling such objects (f.e. mapping them to objects) or switch on the type field to execute some specific logic.

Finally, to my question - which style is the one to be preferred (best-practice) when we want to make the life for consumers as easy as possible and why? Is there a best-practice approach for typed json objects?

Upvotes: 0

Views: 448

Answers (1)

JimT
JimT

Reputation: 116

If you are set on a generic application/json response then I would go with your option #2. That "type" doesn't hurt and can only help clarify what that response is.

Upvotes: 1

Related Questions