Get parents from JSON when using polymorphic associations

39 Views Asked by At

Is there an elegant way to work with JSON response when using polymorphic associations in the below example?

JSON response:

[
  {
    "created_at":"2017-12-13T10:37:36Z",
    "id":16,
    "parent_id":21,
    "parent_type":"app.models.Site",
    "store_number":"0070004900049",
    "updated_at":"2017-12-13T10:37:36Z",
    "value":"fake value",
    "parents":{
      "sites":[
        {
          "created_at":"2017-12-13T10:37:36Z",
          "id":21,
          "section_id":21,
          "updated_at":"2017-12-13T10:37:36Z"
        }
      ]
    }
  }
]

I have 3 models: Parameter as a polymorphic model, with parent_id and parent_type columns, Site.

Here is how I'm truing to test JSON response in ParametersControllerSpec:

Map[] siteSettingsMaps = JsonHelper.toMaps(responseContent());
the(siteSettingsMaps.length).shouldBeEqual(1);
Map siteSetting = siteSettingsMaps[0];

the(siteSetting.get("value")).shouldBeEqual("fake value");
the(siteSetting.get("store_number")).shouldBeEqual(STORE_NUMBER);

It is OK till now. But how to extract parents map ? When I tried like that:

Map<String, Map []> parents = (Map<String, Map []>)siteSettingsMaps[0].get("parents");
Map[] sites = parents.get("sites");
Map site = sites[0];

I got ava.lang.ClassCastException: java.util.ArrayList cannot be cast to [Ljava.util.Map;. Why isn't it a Map ? Should I cast to a List ? I didn't find any methods like getParents(), for example, there is only setter for that. Thank you.

1

There are 1 best solutions below

1
On

It is simpler than you think. At this point, it is a matter of working with JSON, which has no type, other than Map and List:

Map[] siteSettingsMaps = JsonHelper.toMaps(x);
the(siteSettingsMaps.length).shouldBeEqual(1);
Map siteSetting = siteSettingsMaps[0];

the(siteSetting.get("value")).shouldBeEqual("fake value");
the(siteSetting.get("store_number")).shouldBeEqual("0070004900049");

Map parents = (Map) siteSetting.get("parents");
List<Map> sites = (List<Map>) parents.get("sites");
the(sites.size()).shouldBeEqual(1);

The JsonHelper is there for convenience to run tests. You can get really fancy with Jackson or any other JSON library if you like. I generally stay within JavaLite, as this is sufficient.