4

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.

1 Answer 1

1

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.

2
  • Thank you very much for the suggestion, I appreciate it. Would this factory class used to parse objects of one type only or would you use the same factory class for all Services within the application? My application is pretty small, but I would like to know the best practices. Jan 26, 2015 at 9:44
  • 1
    @VladSpreys: Both are possible, or even a combination. You could combine types that are related to each other in one factory, especially if those types can occur in the same JSON message. Jan 26, 2015 at 9:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.