Jackson自定义注解修改字段名

自定义一个注解 JsonName.class

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Retention(RUNTIME)
@Target({FIELD, METHOD})
public @interface JsonName {

	/**
	 * @return 自定义字段名,如果value的值无可见字符,则该注解不起作用
	 */
	String value() default "";
	
	/**
	 * @return 是否覆盖 @JacksonXmlProperty @JsonProperty @JsonGetter @JsonSetter 注解的定义字段名功能
	 */
	boolean override() default true;
}

创建一个实体类 Person.class 并加注解

import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSetter;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;

public class Person {

	@JsonName("nm")
	@JsonProperty(value = "xingming")
	private String name;
	
	@JsonName(value = "nianling", override = false)
	@JacksonXmlProperty(isAttribute = true)
	private String age;
	
	private String sex;
	
	private String testName;
	
	@JsonName(value = "money", override = false)
	@JsonProperty("gongzi")
	private String salary;
	
	@JsonProperty("gongzuo")
	private String work;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public String getSalary() {
		return salary;
	}

	public void setSalary(String salary) {
		this.salary = salary;
	}

	@JsonName(value = "tName", override = false)
	@JsonGetter("test")
	public String getTestName() {
		return testName;
	}

	@JsonName(value = "tName", override = false)
	@JsonSetter("test")
	public void setTestName(String testName) {
		this.testName = testName;
	}

	public String getWork() {
		return work;
	}

	public void setWork(String work) {
		this.work = work;
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + ", sex=" + sex + ", testName=" + testName + ", salary="
				+ salary + ", work=" + work + "]";
	}
	
}

创建序列化修改器 JsonNameBeanSerializerModifier.class

import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import com.fasterxml.jackson.databind.util.NameTransformer;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;

public class JsonNameBeanSerializerModifier extends BeanSerializerModifier {

	@Override
	public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc,
			List<BeanPropertyWriter> beanProperties) {
		List<BeanPropertyWriter> vbeanProperties = new ArrayList<BeanPropertyWriter>(beanProperties);
		beanProperties.clear();
		for (BeanPropertyWriter beanPropertyWriter : vbeanProperties) {
			JsonName jsonName = beanPropertyWriter.getAnnotation(JsonName.class);
			if (jsonName == null) {
				beanProperties.add(beanPropertyWriter);
			} else {
				String value = jsonName.value();
				value = value == null ? "" : value.trim();
				if (value.equals("")) {
					beanProperties.add(beanPropertyWriter);
				} else {
					if (jsonName.override()) {
						beanProperties.add(beanPropertyWriter.rename(new PropertyNameTransformer(value)));
					} else {
						JsonProperty jsonProperty = beanPropertyWriter.getAnnotation(JsonProperty.class);
						JsonGetter jsonGetter = beanPropertyWriter.getAnnotation(JsonGetter.class);
						JacksonXmlProperty jacksonXmlProperty = beanPropertyWriter.getAnnotation(JacksonXmlProperty.class);
						if (jsonProperty != null && !isBlank(jsonProperty.value())
								|| jsonGetter != null && !isBlank(jsonGetter.value())
								|| jacksonXmlProperty != null && !isBlank(jacksonXmlProperty.localName())) {
							beanProperties.add(beanPropertyWriter);
						} else {
							beanProperties.add(beanPropertyWriter.rename(new PropertyNameTransformer(value)));
						}
					}
				}
			}
			// 修改属性名称
		}
		return beanProperties;
	}
	
	private static boolean isBlank(String str) {
		return str == null || str.trim().equals("");
	}

	private static class PropertyNameTransformer extends NameTransformer {
		
		private String value;
		
		public PropertyNameTransformer(String value) {
			super();
			this.value = value;
		}

		@Override
		public String transform(String name) { // 返回新属性名称
			return value;
		}
 
		@Override
		public String reverse(String transformed) {
			return transformed;
		}
	}

}

创建反序列化修改器 JsonNameBeanDeserializerModifier.class

import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.PropertyName;
import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier;
import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition;

import java.util.ArrayList;
import java.util.List;

public class JsonNameBeanDeserializerModifier extends BeanDeserializerModifier {

    @Override
    public List<BeanPropertyDefinition> updateProperties(DeserializationConfig config, BeanDescription beanDesc, List<BeanPropertyDefinition> propDefs) {
    	List<BeanPropertyDefinition> vbeanProperties = new ArrayList<BeanPropertyDefinition>(propDefs);
    	propDefs.clear();
    	for (BeanPropertyDefinition beanPropertyDefinition : vbeanProperties) {
			AnnotatedMethod setter = beanPropertyDefinition.getSetter();
			JsonName jsonName = null;
			if (setter != null) {
				jsonName = setter.getAnnotation(JsonName.class);
			}
			if (jsonName == null) {
				jsonName = beanPropertyDefinition.getField().getAnnotation(JsonName.class);
			}
			if (jsonName == null) {
				propDefs.add(beanPropertyDefinition);
			} else {
				String value = jsonName.value();
				value = value == null ? "" : value.trim();
				if (value.equals("")) {
					propDefs.add(beanPropertyDefinition);
				} else {
					if (!jsonName.override()) {
						propDefs.add(beanPropertyDefinition);
					}
					propDefs.add(beanPropertyDefinition.withName(PropertyName.construct(value)));
				}
			}
		}
    	
        return propDefs;
    }
}

测试

import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

public class Test {

	public static void main(String[] args) throws IOException {
		Person person = new Person();
		person.setName("一个人");
		person.setAge("18");
		person.setSex("1");
		person.setSalary("20000.00");
		person.setTestName("测试人");
		person.setWork("工作");
		
		ObjectMapper mapper = new XmlMapper();
		mapper.setPropertyNamingStrategy(PropertyNamingStrategies.UPPER_CAMEL_CASE);
		SimpleModule seModule = new SimpleModule();
		seModule.setSerializerModifier(new JsonNameBeanSerializerModifier());
		SimpleModule deModule = new SimpleModule();
		deModule.setDeserializerModifier(new JsonNameBeanDeserializerModifier());
		mapper.registerModules(seModule, deModule);
		String value = mapper.writeValueAsString(person);
		System.out.println(value);
		
		Person readValue = mapper.readValue(value, Person.class);
		System.out.println(readValue);
	}
}

打印结果

<Person nianling="18"><Sex>1</Sex><nm>一个人</nm><test>测试人</test><gongzi>20000.00</gongzi><gongzuo>工作</gongzuo></Person>
Person [name=一个人, age=18, sex=1, testName=测试人, salary=20000.00, work=工作]
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值