Jackson 注解 -- 指定输出顺序

– Start

点击此处观看本系列配套视频。


默认情况下,字段的输出顺序和它们在类中的位置一致,我们也可以使用注解 @JsonPropertyOrder 自己指定顺序。

package shangbo.jackson.demo12;

import java.util.Date;

import org.apache.commons.lang3.builder.ToStringBuilder;

import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonPropertyOrder({"firstname", "lastname", "birthday"})
public class Person {
	private String firstname;
	private Date birthday;
	private String lastname;

	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}

	public String getFirstname() {
		return firstname;
	}

	public void setFirstname(String firstname) {
		this.firstname = firstname;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	
	public String getLastname() {
		return lastname;
	}

	public void setLastname(String lastname) {
		this.lastname = lastname;
	}
}
package shangbo.jackson.demo12;

import java.util.Date;

import com.fasterxml.jackson.databind.ObjectMapper;

public class App {
	public static void main(String[] args) throws Exception {
		// 实例化 ObjectMapper 对象
		ObjectMapper objectMapper = new ObjectMapper();

		// 将对象转成 json
		String json = objectMapper.writeValueAsString(newPerson());
		System.out.println(json);

		// 将 json 转成对象
		Person shangbo = objectMapper.readValue(json, Person.class);
		System.out.println(shangbo);
	}

	private static Person newPerson() {
		Person shangbo = new Person();
		shangbo.setFirstname("Bo");
		shangbo.setBirthday(new Date());
		shangbo.setLastname("Shang");

		return shangbo;
	}
}

– 更多参见:Jackson 精萃
– 声 明:转载请注明出处
– Last Updated on 2019-05-25
– Written by ShangBo on 2019-05-25
– End

你可能感兴趣的:(Jackson)