Spring验证字符串值是一个JSON [英] Spring validate string value is a JSON

查看:345
本文介绍了Spring验证字符串值是一个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?

我想要一个验证器,它将尝试将String转换为JSON,如以下示例所示:

I want a validator that will attempt to convert the String to JSON, as in the following example:

如何在Java中将jsonString转换为JSONObject .

推荐答案

可用的验证批注未提供此功能,因此您必须进行自定义实现.该任务分为2个简单步骤:

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格式

有多个库可以解析(因此验证)一个String是否遵循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
  • groupId: org.hibernate
  • artifactId: hibernate-validator

创建用于验证的注释:

@Documented
@Constraint(validatedBy = ContactNumberValidator.class)
@Target( { ElementType.METHOD, 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的中详细描述了此实现.

This implementation is described in detail at Baeldung's.

这篇关于Spring验证字符串值是一个JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆