Skip to content

How to serialize and deserialize AdWords API and Ad Manager API objects

Thanet Knack Praneenararat edited this page May 22, 2019 · 3 revisions

This guide describes how you can serialize and deserialize your AdWords API and Ad Manager API objects using Symfony Serializer into portable formats like JSON and CSV.

Symfony Serializer does not require extra libraries since the Google Ads PHP client library already uses and extends Symfony Serializer classes (e.g., AdWordsNormalizer). It is already listed as one of the dependencies. Symfony Serializer should be found in the /vendor directory once you call composer install or composer require to install all dependencies specified in composer.json.

Note: This guide is confirmed to work with Symfony Serializer up to version 4.

Steps for serializing objects

We will use an AdWords API object as an example and serialize it into a JSON string. Ad Manager objects can be serialized exactly the same way.

The steps to serialize an object into JSON are:

  1. Import Symfony Serializer classes
  2. Instantiate all the related classes
  3. Serialize an AdWords API object into JSON

Import Symfony Serializer classes

At the beginning of your file, import Symfony Serializer classes.

use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;

Instantiate all the related classes

Next, you need to instantiate all the related classes. This can be done once at the top of your file, as they can be used to serialize many objects without the need of re-instantiation. In fact, the only object that you will need to call is $serializer.

$encoders = [new JsonEncoder()];
$normalizers = [new GetSetMethodNormalizer()];
$serializer = new Serializer($normalizers, $encoders);

As you can see, serialization by Symfony is composed of two sub-processes: normalizing and encoding. This is reflected by the fact that two parameters are passed to the constructor of Serializer: $normalizers and $encoders. You can also pass many normalizers and encoders at the same time as described in a later section of this guide.

Serialize an AdWords API object into JSON

Finally, use $serializer to serialize your object by calling serialize() and specify your desired format (json in this case), assuming that you have a Campaign object (named $campaign) that you got from AdWords API via CampaignService.get().

$jsonContent = $serializer->serialize($campaign, 'json');
printf("A campaign object is serialized as: %s\n", $jsonContent);

Congratulations! You have successfully serialized a Campaign object into JSON.

How to change serialization formats

In case you want to serialize objects into formats other than JSON, e.g., CSV, you can achieve that by doing the following:

  1. Import the encoder of the format you want to use. For example, if you want to serialize the object to CSV, you need to import CsvEncoder:

    use Symfony\Component\Serializer\Encoder\JsonEncoder;
    use Symfony\Component\Serializer\Encoder\CsvEncoder;
  2. Pass an instance of the encoder you want to use. In case of CSV, you need to do the following.

    $encoders = [new CsvEncoder()];
    $normalizers = [new GetSetMethodNormalizer()];
    $serializer = new Serializer($normalizers, $encoders);
  3. Finally, tell the serializer to serialize into CSV instead.

    $csvContent = $serializer->serialize($campaign, 'csv');

As mentioned above, you can specify many encoders in case you want to serialize objects into many formats in your application.

$encoders = [new JsonEncoder(), new CsvEncoder(), new XmlEncoder()];

How to deserialize data

To deserialize data, you can call the deserialize() method of the serializer like this:

$encoders = [new CsvEncoder()];
$normalizers = [new GetSetMethodNormalizer()];
$serializer = new Serializer($normalizers, $encoders);
$campaign = $serializer->deserialize($csvData, Campaign::class, 'csv');

We're assuming that $csvData contains a comma-separated-value string representation of an AdWords API Campaign object and you have already imported Campaign of the API version you're using:

use Google\AdsApi\AdWords\v201809\cm\Campaign;

(Optional) Skipping null or empty nested objects when serializing objects

Skipping null and empty nested objects values[^1] when you serialize objects is particularly useful for AdWords API. This is because when you pass null values, they will be ignored by AdWords API, so there's no need to store them in the serialized strings. This section shows how to achieve that.

What you need are to extend the Symfony's GetSetMethodNormalizer class and override the normalize() method to check for empty values and skip them. In particular, the class you need to create would look like this:

use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;

class SkippingEmptyValuesNormalizer extends GetSetMethodNormalizer
{
    public function normalize($object, $format = null, array $context = [])
    {
        $data = parent::normalize($object, $format, $context);

        return array_filter($data, function ($value) {
            if (is_array($value) && empty($value)) {
                return false;
            }
            return !is_null($value);
        });
    }
}

Then, you can use SkippingEmptyValuesNormalizer instead of GetSetMethodNormalizer:

$encoders = [new JsonEncoder()];
$normalizers = [new SkippingEmptyValuesNormalizer()];
$serializer = new Serializer($normalizers, $encoders);

Note: You need to add a namespace at the above of the SkippingEmptyValuesNormalizer file and configure your autoloading so that you can import this class using the use statement. See this guide to configure autoloading via composer.json.

What's next?

See this page to learn more about how to customize Symfony Serializer to fit your specific requirements.

Notes

[^1]: Empty nested objects are those that all of their member variables are unset or null. They are represented as an empty array in the normalization step.