Search code examples
jsonresthateoasjson-serialization

Halarious - Embedded resource field names not being converted with custom naming strategy


I am using the HAL-Specification framework:

https://github.com/surech/halarious

http://confluence.surech.ch/display/HAL/halarious+Home

http://stateless.co/hal_specification.html

It appears that embedded resource field names are not being converted correctly when using a custom naming strategy. Only 'non-HAL' fields are being converted.

Question: Is there a way to ensure custom naming conventions are applied to embedded resources and not just regular fields?

I have the following Gson configuration in a custom MessageBodyWriter...

GsonBuilder builder = new GsonBuilder();
builder.setFieldNamingStrategy(new AllLowercaseFieldNamingStrategy());
builder.registerTypeAdapter(HalResource.class, new HalSerializer()); 
builder.setExclusionStrategies(new HalExclusionStrategy());
Gson gson = builder.create();
try (OutputStreamWriter writer = new OutputStreamWriter(entityStream)) {
    writer.write(gson.toJson(resource, HalResource.class));
}

The AllLowercaseFieldNamingStrategy implementation simply converts the field name to lowercase like so @Override public String translateName(Field f) { return f.getName().toLowerCase(); }

For example:

public class MyResource implements HalResource {
   private final String myField;
   private final MyResource myEmbeddedResource;
   ...
}

results in inconsistent field names (should be all lower case based on naming strategy)...

{
    "myfield": "...",
    "_embedded": {
        "myEmbeddedResource": {...}
    }
} 

Solution

  • My workaround solution was to use the @HalEmbedded annotation and assign a lowercase name directly.

    public class MyResource implements HalResource {
       private final String myField;
       @HalEmbedded(name = "myembeddedresource")
       private final MyResource myEmbeddedResource;
       ...
    }
    

    An issue has been created for the project: https://github.com/surech/halarious/issues/21