Search This Blog

25 July 2016

Validating an expected JSON

    Let's say we are getting a JSON from a service and we want to know if it is following the contract that this service has promised. When we use the JSON we would handle cases of missing keys, but we have to look at the actual response to see if everything is OK with it, and that takes time. What if we want an indication prior to that, that there is something wrong with the data of the JSON. We have implemented a few short methods that take as arguments the JSON that we intend to use and a JSON that is a model of the data that we expect to get. The method traverses the model and checks to see if the JSON that we are going to use matches it.
    We can also use it as part of our automation test for our service.
    How does it work. We have two JSON strings. One is a response that we get from a service and the other is a model of the JSON structure that we expect the service to return - the contract of the service to the clients/users. We check that the response corresponds to the model - if all the keys and structure of the model are present in the response, then it is valid.
Here is a short description of the algorithm:

Validate JSON
Does the key from the model exist in the response:
    No - response is not valid
    Yes:
        is the value a JSON object:
            Yes -> validate JSON object
        is the value a JSON array:
            Yes -> validate JSON array
                    else continue to next key.

    The repository for the project is at GitHub and contains implementation for Objective-C, Java and Go: