{{announcement.body}}
{{announcement.title}}

Jackson Property Custom Naming Strategy

DZone 's Guide to

Jackson Property Custom Naming Strategy

Learn more about this Jackson property custom naming strategy.

· Java Zone ·
Free Resource

To serialize or deserialize to/from POJO, Jackson uses a bean naming convention. To accomplish this, it uses annotations. This annotations cover:

  • Property Naming
  • Property Inclusion
  • Property documentation, metadata
  • Deserialization and Serialization details
  • Deserialization details
  • Serialization details
  • Type handling
  • Object references, identity
  • Meta-annotations

This quick tutorial demonstrates how to use built-in property naming strategies and how to create a custom one.

Property Naming

  •  @JsonProperty (that property will be included) is used to indicate external property name, the name used in the data format (JSON or one of other supported data formats)
    •  @JsonProperty.value: name to use
    •  @JsonProperty.index: physical index to use
    •  @JsonProperty.defaultValue: textual default value defined as metadata.

For instance:

import com.fasterxml.jackson.annotation.JsonProperty;

public class BeanToTest {
	/*
	 * This allows us to have a constant name for the properties inspite of
	 * which naming mechanism we use. i.e. will override whatever
	 * PropertyNamingStrategy we have used and always returns “fieldOne”
	 */
	@JsonProperty("fieldOne")
	private String fieldOne;

	@JsonProperty("fieldTwo")
	private String fieldTwo;

	public String getFieldOne() {
		return fieldOne;
	}

	public void setFieldOne(String fieldOne) {
		this.fieldOne = fieldOne;
	}

	public String getFieldTwo() {
		return fieldTwo;
	}

	public void setFieldTwo(String kFieldTwo) {
		this.fieldTwo = kFieldTwo;
	}

}


@JsonNaming

The@JsonNaming annotation is used to choose the naming strategies for properties in serialization, overriding the default. Using the value element, we can specify any strategy, including custom ones.

In addition to the default, which is LOWER_CAMEL_CASE (e.g. lowerCamelCase), the Jackson library provides us with four built-in property naming strategies for convenience:

  • KEBAB_CASE: This refers to “Lisp”-style lower-case letters with a hyphen as a separator: ids like “lower-case” or “first-name”
  • LOWER_CASE: All letters are lowercase with no separators, e.g. lowercase.
  • SNAKE_CASE: All letters are lowercase with underscores as separators between name elements, e.g. snake_case.
  • UPPER_CAMEL_CASE: All name elements, including the first one, start with a capitalized letter, followed by lowercase ones and there are no separators, e.g. UpperCamelCase.

Note: Usage of the above strategies is with either the per-class annotation or as general naming for all the classes we have.

 @JsonNaming(PropertyNamingStrategy.KebabCaseStrategy.class) is used for the per-class annotation and objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE) as global naming.

The following example shows how to configure both strategies, and I use a unit test to demonstrate:


import java.io.IOException;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;

@RunWith(JUnit4.class)
public class JacksonBeanNamingKebabTest {

	@Test
	public void testBeanNames() throws JsonGenerationException, JsonMappingException, IOException {

		ObjectMapper mapper = new ObjectMapper();
		// Setting PropertyNamingStrategy globally for the ObjectMapper
		mapper.setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE);

		BeanToTest bt = new BeanToTest();
		bt.setFieldOne("field one data.");
		bt.setFieldTwo("field two data.");

		mapper.writeValue(System.out, bt);
	}

	// Setting PropertyNamingStrategy per-class should include @JsonNaming
	@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
	private class BeanToTest {

		private String fieldOne;
		private String fieldTwo;

		public String getFieldOne() {
			return fieldOne;
		}

		public void setFieldOne(String fieldOne) {
			this.fieldOne = fieldOne;
		}

		public String getFieldTwo() {
			return fieldTwo;
		}

		public void setFieldTwo(String kFieldTwo) {
			this.fieldTwo = kFieldTwo;
		}

	}
}


Note: If both global and per-class naming are declared at the same time, per-class will override the global setting.

So, the output:

{
    "field_one":"field one data.",
    "field_two":"field two data."
}


In some conditions, the above methods might not be enough, for instance, if you have your classes generated with some other library or tools (including getters and setters). Let us check the following example.

Assume we have the following class:

public class BeanToTest {
	@JsonProperty("fielOne")
	private String fieldOne;

	@JsonProperty("kFieldTwo")
	private String kFieldTwo;

	public String getFieldOne() {
		return fieldOne;
	}

	public void setFieldOne(String fieldOne) {
		this.fieldOne = fieldOne;
	}

	public String getKFieldTwo() {
		return kFieldTwo;
	}

	public void setKFieldTwo(String kFieldTwo) {
		this.kFieldTwo = kFieldTwo;
	}
}


You may have noticed that the getter/setter for kFieldTwo is slightly different. And it does not obey the bean naming convention, which states that only the first letter should be capital. If you run this, the output will be:

{
    "kfieldTwo":"field constant.",
    "fielOne":"field one data",
    "kFieldTwo":"field constant."
}


One thing to keep in mind is that we have one additional field introduced (kfieldTwo). The robust implementation of Jackson allows adding a custom property naming strategy, which can be helpful in such cases.


import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.cfg.MapperConfig;
import com.fasterxml.jackson.databind.introspect.AnnotatedField;
import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;

@RunWith(JUnit4.class)
public class JacksonBeanNamingCustomTest {

	@Test
	public void testBeanNames() throws JsonGenerationException, JsonMappingException, IOException {

		ObjectMapper mapper = new ObjectMapper();
		mapper.setPropertyNamingStrategy(new PropertyNamingStrategy() {

			@Override
			public String nameForField(MapperConfig<?> config, AnnotatedField field, String defaultName) {
				return field.getName();
			}

			@Override
			public String nameForGetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) {
				return convert(method, defaultName);
			}

			@Override
			public String nameForSetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) {
				return convert(method, defaultName);
			}

			/**
			 * get the class from getter/setter methods
			 * 
			 * @param method
			 * @param defaultName
			 *            - jackson generated name
			 * @return the correct property name
			 */
			private String convert(AnnotatedMethod method, String defaultName) {
				Class<?> clazz = method.getDeclaringClass();
				List<Field> flds = getAllFields(clazz);
				for (Field fld : flds) {
					if (fld.getName().equalsIgnoreCase(defaultName)) {
						return fld.getName();
					}
				}

				return defaultName;
			}

			/**
			 * get all fields from class
			 * 
			 * @param currentClass
			 *            - should not be null
			 * @return fields from the currentClass and its superclass
			 */
			private List<Field> getAllFields(Class<?> currentClass) {
				List<Field> flds = new ArrayList<>();
				while (currentClass != null) {
					Field[] fields = currentClass.getDeclaredFields();
					Collections.addAll(flds, fields);
					if (currentClass.getSuperclass() == null)
						break;
					currentClass = currentClass.getSuperclass();
				}
				return flds;
			}
		});

		BeanToTest bt = new BeanToTest();
		bt.setFieldOne("field one data");
		bt.setKFieldTwo("field constant.");

		mapper.writeValue(System.out, bt);
	}

	private class BeanToTest {
		@JsonProperty("fielOne")
		private String fieldOne;

		@JsonProperty("kFieldTwo")
		private String kFieldTwo;

		public String getFieldOne() {
			return fieldOne;
		}

		public void setFieldOne(String fieldOne) {
			this.fieldOne = fieldOne;
		}

		public String getKFieldTwo() {
			return kFieldTwo;
		}

		public void setKFieldTwo(String kFieldTwo) {
			this.kFieldTwo = kFieldTwo;
		}
	}
}


Output:

{
    "kFieldTwo":"field constant.",
    "fielOne":"field one data"
}


We can see from this that we can override the default naming strategy to our likings.

THIS NAMING STRATEGY CAN ALSO BE APPLIED PER-CLASS LEVEL BY EXTRACTING THE PropertyNamingStrategy TO A NEW FILE AND INCLUDING IT WITH @JsonNaming(…)

Topics:
jackson ,json ,json serialization ,spring ,java ,bean ,annotations ,naming ,custom naming ,property

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}