jackson_json转java

@JsonCreator

标注构造方法或静态工厂方法上 和@JsonProperty@JacksonInject配合使用

	@Test
	public void jsonCreator() throws Exception {
		ObjectMapper objectMapper = new ObjectMapper();
		String jsonStr = "{\"full_name\":\"myName\",\"age\":12}";
		TestPOJO testPOJO = objectMapper.readValue(jsonStr,TestPOJO.class);
		Assert.assertEquals("myName",testPOJO.getName());
		Assert.assertEquals(12, testPOJO.getAge());
	}
 
	public static class TestPOJO{
		private String name;
		private int age;
 
		@JsonCreator
		public TestPOJO(@JsonProperty("full_name") String name,@JsonProperty("age") int age){
			this.name = name;
			this.age = age;
		}
		public String getName() {
			return name;
		}
		public int getAge() {
			return age;
		}
	}

在静态工厂方法上 
 

	@Test
	public void jsonCreator() throws Exception {
		ObjectMapper objectMapper = new ObjectMapper();
		String jsonStr = "{\"name\":\"myName\",\"birthday\":1416299461556}";
		TestPOJO testPOJO = objectMapper.readValue(jsonStr,TestPOJO.class);
		Assert.assertEquals("myName",testPOJO.getName());
		System.out.println(testPOJO.getBirthday());
	}
 
	public static class TestPOJO{
		private String name;
		private Date birthday;
 
		private TestPOJO(String name,Date birthday){
			this.name = name;
			this.birthday = birthday;
		}
 
		@JsonCreator
		public static TestPOJO getInstance(@JsonProperty("name") String name,@JsonProperty("birthday") long timestamp){
			Date date = new Date(timestamp);
			return new TestPOJO(name,date);
		}
 
		public String getName() {
			return name;
		}
 
		public Date getBirthday() {
			return birthday;
		}
	}

授权式构造器 比较常用这个构造器只有一个参数

	@Test
	public void jsonCreator() throws Exception {
		ObjectMapper objectMapper = new ObjectMapper();
		String jsonStr = "{\"full_name\":\"myName\",\"age\":12}";
		TestPOJO testPOJO = objectMapper.readValue(jsonStr,TestPOJO.class);
		Assert.assertEquals("myName",testPOJO.getName());
		Assert.assertEquals(12,testPOJO.getAge());
	}
 
	public static class TestPOJO{
		private String name;
		private int age;
		@JsonCreator
		public TestPOJO(Map map){
			this.name = (String)map.get("full_name");
			this.age = (Integer)map.get("age");
		}
 
		public String getName() {
			return name;
		}
 
		public int getAge() {
			return age;
		}
	}

猜你喜欢

转载自blog.csdn.net/maqingbin8888/article/details/82752080