版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012326462/article/details/83020222
@JsonAnySetter @JsonAnyGetter,主要用来获取反序列时未匹配上的字段,作用在set和get方法上
用法如下:
package com.xhx.json.entity3;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import java.util.HashMap;
import java.util.Map;
public class Phone {
private String id;
private String model;
private Map<String,Object> other = new HashMap<>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
@JsonAnyGetter
public Map<String, Object> getOther() {
return other;
}
/**
* 没有匹配上的反序列化属性,放到这里
* @param key
* @param value
*/
@JsonAnySetter
public void setOther(String key, Object value) {
this.other.put(key,value);
}
@Override
public String toString() {
return "Phone{" +
"id='" + id + '\'' +
", model='" + model + '\'' +
", other=" + other +
'}';
}
}
@JsonAnySetter 的方法,用两个参数接收,一个时key,一个时value
测试方法及结果:
@Test
public void testJson6() throws Exception{
Map<String,Object> map = new HashMap<>();
map.put("id","abdae");
map.put("name","我的");
map.put("model","nokia");
map.put("size","6.0");
String s = mapper.writeValueAsString(map);
Phone phone = mapper.readValue(s, Phone.class);
System.out.println(phone);
//Phone{id='abdae', model='nokia', other={size=6.0, name=我的}}
}