Json序列化与反序列化

自己封装一个工具类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 object(String content, Class 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;
}

你可能感兴趣的:(Json序列化与反序列化)