在系統交互之間,采用Json的數據格式執行協議,來完成數據傳輸,算是前置校驗吧
省去schema文件的編寫,大致內容如下,網上copy的
{
...
"vegetables": {
"type": "array",
"items": { "$ref": "#/definitions/veggie" }
}
},
"definitions": {
"veggie": {
"type": "object",
"required": [ "veggieName", "veggieLike" ],
"properties": {
"veggieName": {
"type": "string",
"description": "The name of the vegetable."
},
"veggieLike": {
"type": "boolean",
"description": "Do I like this vegetable?"
}
...}
只使用代碼描述,不在進行過多贅述,我不太喜歡說話
抽象出大致要使用的頂級接口Complier
,好了我似乎特別喜歡Complier
,好多都是它。
public interface Complier {
void complie(byte[] bytes);
}
實現頂級接口Complier
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import com.github.fge.jsonschema.main.JsonSchema;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
/**
* @Description //TODO
* @Author taren.Tian
* @Date 14:59 2019/8/16
**/
public class MyDataComplier implements Complier {
private JsonSchema schema;
private final ObjectMapper objectMapper = new ObjectMapper();
public MyDataComplier() {
try {
//讀入自定義的schemas文件
JsonNode sh = objectMapper.readTree(this.getClass()
.getClassLoader()
.getResourceAsStream("schemas/yourJson.json"));
final JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
schema = factory.getJsonSchema(sh);
} catch (Exception e) {
}
}
@Override
public void complie(byte[] bytes) {
try {
JsonNode jsonNode = objectMapper.readTree(bytes);
//先校驗數據的格式 然后進行業務邏輯的處理
ProcessingReport report = schema.validate(jsonNode);
if (!report.isSuccess()) {
throw new Exception(report.toString());
}
//doSomething()
} catch (Exception e) {
}
}
}
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。