Spring 验证字符串值是一个 JSON [英] Spring validate string value is a JSON
问题描述
我的配置文件中有一些值,它应该是一个 JSON(将作为字符串加载).
I have some value from my configuration file, that should be a JSON (which will be loaded as a String).
我希望 Spring 在注入之前验证该值确实是有效的 JSON,否则会引发错误.
I'd like Spring to validate that this value is indeed a valid JSON before injecting it and throw an error else.
我已经阅读了存在的验证注释,例如 - @NotNull
、@Size
、@Min
、@Max
、@Email
、@NotEmpty
等
I've read about the validation annotations that exist, such as - @NotNull
, @Size
, @Min
, @Max
, @Email
, @NotEmpty
etc.
有没有办法创建自定义验证器?
Is there any way to create a custom validator?
我想要一个尝试将字符串转换为 JSON 的验证器,如下例所示:Java 中如何将 jsonString 转换为 JSONObject.
I want a validator that will attempt to convert the String to JSON, as in the following example: How to convert jsonString to JSONObject in Java.
推荐答案
这不是由可用的验证注释提供的,因此您必须寻求自定义实现.任务分为两个简单的步骤:
This is not provided by available validation annotations, therefore you have to go for a custom implementation. The task is divided into 2 simple steps:
1.给定的 String 是否为 JSON 格式
有多个库可以解析(因此验证)字符串是否遵循 JSON 语法标准.让我们以我最喜欢的 GSON 为例(有 许多).这取决于您当前使用的库:
There are multiple libraries that are able to parse (therefore validate) a String whether follows the JSON syntax standard. Let's use my favourite GSON for example (there are many). It depends on what library do you currently use:
String string = "{\"foo\":\"bar\"}"
JsonParser jsonParser = new JsonParser();
try {
jsonParser.parse(string); // valid JSON
} catch (JsonSyntaxException ex) {
/* exception handling */ // invalid JSON
}
2.自定义验证注释
从提供启用验证的依赖项开始:
Start with providing a dependency enabling validations:
- groupId:
org.hibernate
- artifactId:
hibernate-validator
创建用于验证的注释:
@Documented
@Constraint(validatedBy = JsonStringValidator.class)
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface JsonString {
String message() default "The String is not in JSON format";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
... 以及通过注解处理验证的验证器:
... and the validator handling the validation through the annotation:
public class JsonStringValidator implements ConstraintValidator<JsonString, String> {
@Override
public void initialize(JsonString jsonString) { }
@Override
public boolean isValid(String string, ConstraintValidatorContext context) {
// Use an implementation from step 1. A brief example:
try {
new JsonParser().parse(string);
return true; // valid JSON, return true
} catch (JsonSyntaxException ex) {
/* exception handling if needed */
}
return false; // invalid JSON, return false
}
}
用法非常简单:
@JsonString
private String expectedJsonString
Baeldung's 中详细描述了此实现.
This implementation is described in detail at Baeldung's.
这篇关于Spring 验证字符串值是一个 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!