有时候JSON 数据格式需要校验是否合法,我们可以使用 JsonSchema 来校验数据是否合法。
引入 pom.xml
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.networknt.schema.JsonSchema;
import com.networknt.schema.JsonSchemaFactory;
import com.networknt.schema.SpecVersion;
import com.networknt.schema.ValidationMessage;
import java.util.Set;
public class ValidJson {
public static void main(String[] args) throws JsonProcessingException {
String json="{\n" +
" \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n" +
" \"title\": \"Order Event\",\n" +
" \"description\": \"Order event schema for example\",\n" +
" \"required\": [\"order_id\", \"total_price\", \"products\" ],\n" +
" \"properties\": {\n" +
" \"order_id\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"event\": {\n" +
" \"enum\": [\"PLACED\", \"DELIVERED\", \"RETURNED\"],\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"total_price\": { \n" +
" \"type\": \"number\",\n" +
" \"minimum\": 0\n" +
" },\n" +
" \"products\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"additionalProperties\": true,\n" +
" \"required\": [\"product_id\", \"price\"],\n" +
" \"minItems\": 1,\n" +
" \"properties\": {\n" +
" \"product_id\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"price\": {\n" +
" \"type\": \"number\",\n" +
" \"minimum\": 0\n" +
" },\n" +
" \"quantity\": {\n" +
" \"type\": \"integer\"\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
String json2="{\n" +
" \"order_id\":\"order134\",\n" +
" \"event\": \"PLACED\",\n" +
" \"products\": [\n" +
" {\n" +
" \"product_id\": \"product_1\",\n" +
" \"price\":20.5,\n" +
" \"quantity\":2\n" +
" }\n" +
" ],\n" +
" \"total_price\": 41\n" +
"}";
JsonSchema jsonSchema = jsonSchema(json);
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(json2);
String str= validateJson(jsonSchema,jsonNode);
System.err.println(str);
}
public static JsonSchema jsonSchema(String schema) {
return JsonSchemaFactory
.getInstance( SpecVersion.VersionFlag.V7 )
.getSchema(schema);
}
public static String validateJson(JsonSchema jsonSchema, JsonNode jsonNode){
Set<ValidationMessage> errors = jsonSchema.validate(jsonNode);
return errors.toString();
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
- 72.
- 73.
- 74.
- 75.
- 76.
- 77.
- 78.
- 79.
- 80.
- 81.
- 82.
- 83.
- 84.
- 85.
- 86.
- 87.
- 88.
- 89.
- 90.