Design Pattern to parse array of objects

design-patternsweb services

What is considered a good practice to parse an array of objects returned by an API?

I am creating a RESTfull web service and a client which is meant to work with this service.

One of my REST services returns a JSON array in the following format:

{
  "objectsArray": [
    {
      "PropertyA": 10,
      "PropertyB": "A String",
      "PropertyC": true,
    },
    {
      "PropertyA": 20,
      "PropertyB": "Another String",
      "PropertyC": false,
    }
  ]
}

In my client I would like to parse this JSON array and map it to the model, but I am not sure where to place the parsing logic to keep the loose coupling.

What I already have:

  1. Model class. From the example above I would like to get two objects
    of this class. If I had a single object returned by the API, I would've added a constructor which could consume JSON, but adding a method to parse an array of objects doesn't feel right.
  2. REST Client class. This class is meant to make REST calls and deliver the result, I would like to make it re-usable, so I don't
    want it to know anything about my model.
  3. View controller. I would make the service call from here, then I want to parse the received data and display it on the view. Adding
    the parsing logic here seems to be the most logical solution, but
    doesn't feel quite right.

What are the good practices or design patterns for such a task? Do I need to create an extra class for this?

Thank you in advance.

Best Answer

I would put the parsing code in a factory class that knows how to create both a single instance of the Model class from the JSON as well as how to create a sequence of Model class instances from the JSON.
This is based on the assumption that you already know what objects are being represented by the JSON. If you don't know exactly what objects the JSON represents, the factory class is the easiest mechanism that can be extented to take almost arbitrary JSON and create the correct objects for that.

The factory class would be used by your View controller, where you also receive the JSON.