栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java 使用JSONSchema入门学习

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java 使用JSONSchema入门学习

Match.json

{
  "type": "object",
  "properties": {
    "number": { "type": "number" },
    "street_name": { "type": "string" },
    "street_type": { "enum": ["Street", "Avenue", "Boulevard"] }
  }
}

test.json

{
  "number": 1600,
  "street_name": "Pennsylvania",
  "street_type": "Avenue"
}

Json文件的位置放在resources目录下即可

校验代码

package com.learning.jonchema;



import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.everit.json.schema.Schema;
import org.everit.json.schema.ValidationException;
import org.everit.json.schema.loader.SchemaLoader;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.junit.Test;

import java.io.InputStream;



public class TestJson {

    @Test
    public void TestJson() {

        //这个就是你设定的标准JSON
        InputStream standard = getClass().getResourceAsStream("/Match.json");

        //这个是你打算验证的JSON,这里我也用一份文件来存放,你也可以使用string或者jsonObject
        InputStream verification = getClass().getResourceAsStream("/test.json");

        JSONObject standardJSON = new JSONObject(new JSONTokener(standard));
        JSONObject verificationJSON = new JSONObject(new JSONTokener(verification));

        Schema schema = SchemaLoader.load(standardJSON);


        try {
            schema.validate(verificationJSON);
            System.out.println("校验成功!");
        } catch (ValidationException e) {
            System.out.println("校验失败!");
            System.out.println(e.getErrorMessage());
        }
    }
}



运行结果是 校验成功!

当把test.json文件的内容换成

{
  "number": "1600",
  "street_name": "Pennsylvania",
  "street_type": "Avenue"
}

运行结果是
校验失败!
expected type: Number, found: String, 因为提供的号码类型错误,则无效
更多的校验规则可以看JSONSchema规范(中文版)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1014500.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号