自己封装一个工具类
OjmService
,对ObjectMapper进行操作。
要加上@Service
或者@Component
注解,使用时要注入
package com.fzy.javastudy.spring.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.IOException;
@Slf4j
@Service
public class OjmService {
@Resource
private ObjectMapper objectMapper;
public String json(Object object) {
try {
return objectMapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
log.error("json parse error - {}", object);
}
return null;
}
public <T> T object(String content, Class<T> valueType) {
try {
return objectMapper.readValue(content, valueType);
} catch (IOException e) {
log.error("[{}] cannot be parsed to [{}]", content, valueType);
}
return null;
}
}
对象的格式
@JsonProperty("name")
:json序列化是以name
为名称的
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserEntity {
@JsonProperty("id")
private String id;
@JsonProperty("user_name")
private String userName;
@JsonProperty("pwd")
private String password;
@JsonProperty("age")
private Integer age;
@JsonProperty("email")
private String email;
}
网友评论