jackson 笔记
所属分类 jackson
浏览量 100
json 序列化和反序列化
https://github.com/FasterXML/jackson
jackson 2.13.5
jackson-core jackson-annotations jackson-databind
jackson-core
核心包,提供基于"流模式"解析的相关 API,它包括 JsonPaser 和 JsonGenerator
jackson-annotations 注解包,提供标准注解功能
jackson-databind 数据绑定包
提供基于 对象绑定 解析的相关 API (ObjectMapper) 和 树模型 解析的相关 API (JsonNode)
Jackson JSON 对象绑定
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
String str = objectMapper.writeValueAsString(pet);
Pet pet2 = objectMapper.readValue(str,Pet.class);
List< Pet> pets = new ArrayList< >();
pets.add(pet);
pets.add(pet2);
str = objectMapper.writeValueAsString(pets);
Pet[] petArr = objectMapper.readValue(str, Pet[].class);
pets = objectMapper.readValue(str,new TypeReference< List< Pet>>(){});
str = objectMapper.writeValueAsString(pet);
Map< String, Object> jsonMap = objectMapper.readValue(str,new TypeReference< Map< String,Object>>(){});
java.util.Date对象序列化 默认转为 long型的值
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
objectMapper.setDateFormat(dateFormat);
Jackson JSON 树模型
JsonNode jsonNode = objectMapper.readValue(str, JsonNode.class);
jsonNode = objectMapper.readTree(str);
JsonNode idNode = jsonNode.get("id");
long id = jsonNode.get("id").asLong();
String name = jsonNode.get("name").asText();
int age = jsonNode.get("age").asInt();
// JsonNode 不可变 ,子类 ObjectNode
ObjectNode petNode = objectMapper.createObjectNode();
petNode.put("id",id);
petNode.put("name",name);
petNode.put("age",age);
petNode.remove("age");
Iterator< String> fieldNames = jsonNode.fieldNames();
JsonNode 可表示 对象 或 数组
get 方法 传入 string 访问字段,传入int ,根据索引访问数组
str = objectMapper.writeValueAsString(pets);
// 数组
jsonNode = objectMapper.readTree(str);
for(int i=0;i< jsonNode.size();i++){
System.out.println(jsonNode.get(i));
}
Map< String,Pet> petMap = new HashMap< >();
petMap.put("pet1",pet);
str = objectMapper.writeValueAsString(petMap);
jsonNode = objectMapper.readTree(str);
// JSON路径表达式 必须 / 开头
JsonNode nameNode = jsonNode.at("/pet1/name");
Jackson注解
Read + Write注解
@JsonIgnore
不读取或写入属性
public class PersonIgnore {
@JsonIgnore
public long personId = 0;
public String name = null;
}
@JsonIgnoreProperties({"firstName", "lastName"})
public class PersonIgnoreProperties {
public long personId = 0;
public String firstName = null;
public String lastName = null;
}
@JsonIgnoreType
@JsonAutoDetect 读写对象时包括非public修饰的属性
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY )
public class PersonAutoDetect {
private long personId = 123;
public String name = null;
}
Read注解
@JsonSetter
@JsonAnySetter
@JsonCreator
@JacksonInject
@JsonDeserialize 指定自定义反序列化器类
public class PersonImmutable {
private long id = 0;
private String name = null;
@JsonCreator
public PersonImmutable(
@JsonProperty("id") long id,
@JsonProperty("name") String name ) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
}
Write注解
@JsonInclude
@JsonGetter
@JsonAnyGetter
@JsonPropertyOrder
@JsonRawValue
@JsonValue
@JsonSerialize 指定自定义序列化类
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class PersonInclude {
public long personId = 0;
public String name = null;
}
public class PersonGetter {
private long personId = 0;
@JsonGetter("id")
public long personId() { return this.personId; }
@JsonSetter("id")
public void personId(long personId) { this.personId = personId; }
}
@JsonPropertyOrder({"name", "personId"})
public class PersonPropertyOrder {
public long personId = 0;
public String name = null;
}
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.text.SimpleDateFormat;
public class JacksonUtil {
static final ObjectMapper objectMapper = new ObjectMapper();
private static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
static{
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// null 字段不输出
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
objectMapper.setDateFormat(new SimpleDateFormat(DATETIME_FORMAT));
}
public static T readValue(String content, Class valueType)throws Exception{
return objectMapper.readValue(content,valueType);
}
public static String toJsonString(Object obj,boolean pretty)throws Exception{
if(obj==null){
return null;
}
if(pretty){
return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
}
return objectMapper.writeValueAsString(obj);
}
}
https://gitee.com/dyyx/work2024/blob/master/demo/appdemo/src/main/java/demo/jackson/JacksonDemo.java
https://gitee.com/dyyx/work2024/blob/master/demo/appdemo/src/main/java/demo/util/JacksonUtil.java
上一篇
下一篇
家常炒挂面
JPA常用注解
Springboot 过滤器 拦截器 全局异常处理
mybatis之MappedStatement getBoundSql
Mybatis SqlSource 与 BoundSql
小红书视频下载