Jackson反序列化json字符串到java对象对Object类型和抽象类处理

  • Post author:
  • Post category:java


Jackson反序列化json字符串到java对象对Object类型和抽象类处理

1)java对象的属性为Object,将会转化为LinkedHashMap

public class ObjectTest {
	private static final Logger logger = LoggerFactory.getLogger(ObjectTest.class);

	@Test
	public void objectTest() throws JsonProcessingException {
		Person person = new Person();
		person.setName("zhibin");
		List<Object> pets = new ArrayList<>();
		pets.add(Pet.builder().name("mimi").age(2).build());
		pets.add(Pet.builder().name("wangwang").age(3).build());
		person.setPets(pets);
		//mapper
		ObjectMapper mapper = new ObjectMapper();
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		String json = mapper.writeValueAsString(person);
		//{"name":"zhibin","pets":[{"age":2,"name":"mimi"},{"age":3,"name":"wangwang"}]}
		logger.info(json);
		Person person2 = mapper.readValue(json, Person.class);
		//Object will change to LinkedHashMap
		logger.info("data: {}", person2);
	}

	@Data
	static class Person {
		private String name;
		private List<Object> pets;
	}

	@Data
	@Builder
	static class Pet {
		private int age;
		private String name;
	}
}

2)抽象类无法被反序列化,因为抽象类没有可执行的构造函数

因此,需要处理的Json的java对象,属性中不能包含抽象类

public class AbstractTest {
	private static final Logger logger = LoggerFactory.getLogger(AbstractTest.class);

	@Test
	public void objectTest() throws JsonProcessingException {
		Person person = new Person();
		person.setName("zhibin");
		List<Pet> pets = new ArrayList<>();
		Cat cat = new Cat();
		cat.setName("mimi");
		cat.setAge(2);
		pets.add(cat);
		Dog dog = new Dog();
		dog.setName("wangwang");
		dog.setAge(3);
		pets.add(dog);
		person.setPets(pets);

		//mapper
		ObjectMapper mapper = new ObjectMapper();
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		String json = mapper.writeValueAsString(person);
		//{"name":"zhibin","pets":[{"age":2,"name":"mimi"},{"age":3,"name":"wangwang"}]}
		logger.info(json);

		Person person2 = mapper.readValue(json, Person.class);
		//Object will change to LinkedHashMap
		logger.info("data: {}", person2);
	}

	@Data
	static class Person {
		private String name;
		private List<Pet> pets;
	}

	abstract static class Pet {
		protected int age;
		protected String name;
		public int getAge() {
			return age;
		}
		public void setAge(int age) {
			this.age = age;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
	}
	static class Cat extends Pet {
	}
	static class Dog extends Pet {
	}
}



版权声明:本文为loophome原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。