rapidjson Schema

这篇博客主要通过实例介绍如何使用rapidjson库进行Schema解析,帮助理解其在JSON处理中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

博客搬家,原地址:https://langzi989.github.io/2017/05/27/rapidjsonSchema/

本系列文章以例子的方式进行呈现。

/*
* JsonSchema本质上是一个json,其作用是用于校验Json,使用schema对json进行校验,
* 可以让代码安全的去当问DOM,而不需要去检查类型或者键值的存在等等。这也能确保输
* 出的json符合特定的schema。
*/
#include "rapidjson/schema.h"
#include "rapidjson/stringbuffer.h"
#include <stdio.h>
#include <string>
#include <string.h>

using namespace std;
using namespace rapidjson;

/*使用JsonSchema校校验json格式的流程:
*       1. 将schema(模板)解析成一个Document
*       2. 然后将Document编译成一个SchemaDocument
*       3. 通过上述SchemaDocument创建一个SchemaValidator。
*       4. 然后通过document.Accept(validator)去校验一个json,获取校验结果。
*注意:
*       1. 一个SchemaDocument能被多个SchemaValidator引用,他不会被SchemaValidator修改。
*       2. 可以重复使用SchemaValidator校验多个文件。在校验其他文件之前,必须先调用validator.Reset()。
*JsonSchema的格式:
*       1. JsonSchema实质上是一个json数据。
*       2. JsonSchema与其他json数据不同的是它在每一个对象和元素中定义了他们的类型type,属性(如object的properties,以及integer的minimum等等),
*           同时,我们可以通过JsonSchema对json的值的类型以及取值范围等进行限定。schema中必须的值需要显示的声明在required中。
*/

bool ValidateJson() {
  string testSchema = "{\"type\":\"object\", \"properties\":{\"code\":{\"type\":\"string\"}, \"int\":{\"type\":\"integer\", \"minimum\":0}}, \"required\":[\"int\",\"code\"]}";
  Document sd;
  if (sd.Parse(testSchema.c_str()).HasParseError()) {
    printf("jsonSchema is not valid : %s", testSchema.c_str());
    return false;
  }

  //创建SchemaDocument
  SchemaDocument schema(sd);

  Document d;
  if (d.Parse("{\"code\":123, \"int\":1}").HasParseError()) {
    printf("Document is not a valid json");
    return false;
  }

  SchemaValidator validator(schema);

  if (!d.Accept(validator)) {
    StringBuffer sb;
    validator.GetInvalidSchemaPointer().StringifyUriFragment(sb);
    printf("Invalid schema: %s\n", sb.GetString());
    printf("Invalid keyword: %s\n", validator.GetInvalidSchemaKeyword());
    sb.Clear();
    validator.GetInvalidDocumentPointer().StringifyUriFragment(sb);
    printf("Invalid document:%s\n ", sb.GetString());
    return false;
  } else {
    printf("符合schemas模式\n");
    return true;
  }
}

int main() {
  ValidateJson();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值