如何在Jackson中验证特定的JSON结构? [英] How to validate a specific json structure in Jackson?

查看:41
本文介绍了如何在Jackson中验证特定的JSON结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种方法来验证特定格式化的json,该json可以使用Jackson表示类(在我的案例中是Book类)字符串。有什么方法可以使用jsonSchema来实现这一点吗?或者我必须用不同的方式来做

ObjectMapper mapper = new ObjectMapper(); JsonSchema jsonSchema = mapper.generateJsonSchema(Book.class);

推荐答案

编辑

为此,您需要使用第三方库。

https://github.com/fge/json-schema-validator

    ObjectMapper objectMapper = new ObjectMapper();
    // this line will generate JSON schema from your class
    JsonNode schemaNode = objectMapper.generateJsonSchema(StageDetail.class).getSchemaNode();

    // make your JSON to JsonNode
    JsonNode jsonToValidate = JsonLoader.fromString(JSON_TO_VALIDATE);

    // validate it against the schema
    ProcessingReport validate = JsonSchemaFactory.byDefault().getJsonSchema(schemaNode).validate(jsonToValidate);
    // validate.messages contains error massages
    System.out.println("Valid? " + validate.isSuccess());

这篇关于如何在Jackson中验证特定的JSON结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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