io.katharsis.jackson.serializer.DataLinksContainerSerializer Maven / Gradle / Ivy
package io.katharsis.jackson.serializer;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import io.katharsis.queryParams.include.Inclusion;
import io.katharsis.queryParams.params.IncludedRelationsParams;
import io.katharsis.resource.field.ResourceField;
import io.katharsis.resource.registry.ResourceRegistry;
import io.katharsis.response.ContainerType;
import io.katharsis.response.DataLinksContainer;
import io.katharsis.response.RelationshipContainer;
import java.io.IOException;
/**
* Serializes a links field of a resource in data field of JSON API response.
* Additionally, it solves a problem
* mentioned in #220
* where an included relationship should forced inclusion of relationship details.
*
* @see DataLinksContainer
*/
public class DataLinksContainerSerializer extends JsonSerializer {
public DataLinksContainerSerializer(ResourceRegistry resourceRegistry) {
}
@Override
public void serialize(DataLinksContainer dataLinksContainer, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
for (ResourceField field : dataLinksContainer.getRelationshipFields()) {
boolean forceInclusion = shouldForceFieldInclusion(dataLinksContainer, field, dataLinksContainer.getIncludedRelations());
RelationshipContainer relationshipContainer =
new RelationshipContainer(dataLinksContainer, field, forceInclusion);
gen.writeObjectField(field.getJsonName(), relationshipContainer);
}
gen.writeEndObject();
}
private boolean shouldForceFieldInclusion(DataLinksContainer dataLinksContainer, ResourceField field, IncludedRelationsParams includedRelations) {
if (includedRelations != null) {
for (Inclusion inclusion : includedRelations.getParams()) {
if (field.getJsonName().equals(inclusion.getPathList().get(0))
&& dataLinksContainer.getContainerType().equals(ContainerType.TOP)) {
return true;
} else if (dataLinksContainer.getContainerType().equals(ContainerType.INCLUDED)
&& inclusion.getPathList().size() > 1
&& field.getJsonName().equals(inclusion.getPathList().get(1))) {
return true;
}
}
}
return false;
}
public Class handledType() {
return DataLinksContainer.class;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy