– Start
点击此处观看本系列配套视频。
我们也可以使用 Map 存储 JSON, 而不用创建对应的对象。
package shangbo.jackson.demo16;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.builder.ToStringBuilder;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
public class Person {
private Map<String, Object> properties = new HashMap<>();
@JsonAnySetter
public void set(String fieldName, Object val) {
this.properties.put(fieldName, val);
}
@JsonAnyGetter
public Object get(String fieldName) {
return this.properties.get(fieldName);
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
package shangbo.jackson.demo16;
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 = "{\"firstname\":\"Bo\",\"lastname\":\"Shang\"}";
// 将 json 转成对象
Person shangbo = objectMapper.readValue(json, Person.class);
System.out.println(shangbo);
}
}
– 更多参见:Jackson 精萃
– 声 明:转载请注明出处
– Last Updated on 2019-05-26
– Written by ShangBo on 2019-05-26
– End