<dependency> <groupId>com.github.fge</groupId> <artifactId>json-schema-validator</artifactId> <version>2.2.8</version> </dependency> json { "age": 25, "email": "zhangsan@example.com" } json { "type": "object", "properties": { "name": {"type": "string"}, "age": {"type": "integer"}, "email": {"type": "string", "format": "email"} }, "required": ["name", "age", "email"] } import com.github.fge.jsonschema.core.exceptions.ProcessingException; import com.github.fge.jsonschema.core.report.ProcessingReport; import com.github.fge.jsonschema.main.JsonSchema; import com.github.fge.jsonschema.main.JsonSchemaFactory; import com.github.fge.jsonschema.main.JsonValidator; public class JsonValidatorExample { public static void main(String[] args) throws IOException, ProcessingException { JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); JsonValidator validator = factory.getValidator(); JsonNode data = objectMapper.readTree(jsonData); JsonNode schema = objectMapper.readTree(jsonSchema); JsonSchema jsonSchema = factory.getJsonSchema(schema); ProcessingReport report = jsonSchema.validate(data); if (report.isSuccess()) { } else { report.forEach(System.out::println); } } } <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.7</version> </dependency> json { "age": 25, "email": "zhangsan@example.com" } public class Person { private String name; private int age; private String email; // Getter and Setter methods } import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; public class GsonValidatorExample { public static void main(String[] args) { Gson gson = new Gson(); try { Person person = gson.fromJson(jsonData, Person.class); } catch (JsonSyntaxException e) { } } }


上一篇:
下一篇:
切换中文