Spring boot @ConfigurationProperties 转换为json并编码

问题描述 投票:0回答:1

我在 yaml 中有一个属性

mail:
  hostname: [email protected]
  port: 9000
  from: [email protected]

我想创建一个 Spring Bean 并将它们注入到必要的地方。 我想要一个辅助方法来以不同的格式呈现这个 bean

@Setter
@ToString
@Configuration
@ConfigurationProperties(prefix = "mail")
public class ClientProperties {
    private String hostName;
    private int port;
    private String from;
    private String time = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

    public String toJson() throws JsonProcessingException {
        return new ObjectMapper().writeValueAsString(this.toString());
    }

    public String getDigest() throws JsonProcessingException {
        String fromJson = this.toJson();
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(fromJson.getBytes());
            byte[] b = md.digest();
            result = java.util.Base64.getEncoder().encodeToString(b);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return result;
    }
}

我使用 Jackson 进行转换,但我听说为了简单的事情最好使用 GSON。 你能帮我理解如何从对象本身创建一个 json 因为 这个不行

    public String toJson() throws JsonProcessingException {
        return new ObjectMapper().writeValueAsString(this.toString());
    }

我在这个方法 getDigest() 中做错了什么? 使用类似的东西更好吗

 ObjectMapper mapper = new ObjectMapper();
 byte[] body = mapper.writeValueAsBytes(jsonString);
 byte[] digest = DigestUtils.md5Digest(body); 
 String encodeMD5String = Base64.getEncoder().encodeToString(digest);
java spring spring-boot jackson
1个回答
0
投票

对于这个辅助方法:

public String toJson() throws JsonProcessingException {
    return new ObjectMapper().writeValueAsString(this.toString());
}

应该使用对象,而不是对象的字符串版本。 (并且可能需要忽略该辅助方法以避免无休止的递归。)

@JsonIgnore
public String toJson() throws JsonProcessingException {
    return new ObjectMapper().writeValueAsString(this);
}

getDigest()
方法类似。

此外,当 Jackson 位于类路径中时,

ObjectMapper
将是一个可用的 Spring bean,因此应该在需要的地方注入该 bean,而不是每次都创建一个新实例。

© www.soinside.com 2019 - 2024. All rights reserved.