c++-json(0)-rapidjson-read-write-实例代码

RapidJson是一个跨平台的c++的json的解析器和生成器;
相比较jsoncpp库,RapidJson只有头文件,容易安装;
RapidJSON 不依赖STL和boost等外部库独立;
只使用如下文件:, , , , , ;
高性能,使用模版及内联函数去降低函数调用开销、内部经优化的 Grisu2 及浮点数解析实现、可选的 SSE2/SSE4.2 支持.

0.添加库头文件到工程文件中


   

  属性->c/c++/附加包含目录:
       D:\C++-httpserver-json-redis\httpserver_json\httpserver_json\rapidjson


 

#include 
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"

using namespace std;
using namespace rapidjson;



  

1.创建json文件

   

 没有文件创建文件,有文件读取文件.

CFile  m_fileJson;
BOOL  flage_open = m_fileJson.Open(strInFileName , CFile::modeRead);
if(flage_open == FALSE)//说明该json文件没有提前被创建
{
	
	m_fileJson.Open(strInFileName,CFile::modeCreate);
}
else
{
    DWORD len = m_fileJson.GetLength();
    char* filebuf = new char(len + 1);
    filebuf[len] = '\0';                            //终止字符串,用于输出
    m_fileJson.SeekToBegin();
    m_fileJson.Read(filebuf, sizeof(char) * len);  //缓冲区的长度
     
}
m_fileJson.Close();

  

2.读取的json文件
 


{
  "35KV_JXNEPYHBDS_102EDJX": {
    "MPf": "0",
    "device_id": "35KV_JXNEPYHBDS_102EDJX",
    "F": "50",
    "I0": "2.8799999",
    "UA": "5.92",
    "UB": "0.01",
    "UC": "5.91",
    "P": "0",
    "JXDDY": "0",
    "Q": "0",
    "JXGDY": "0",
    "event_time_utc": "20220620T070750Z",
    "Ia": "6.24",
    "BreakStatus": "1",
    "Ic": "6.72",
    "U0": "3.4299998",
    "event_time": "2022-06-20 15:07:50"
  },
  "35KV_ZHUJINGKOU_YHJX": {
    "MPf": "0.644",
    "JXGFE": "0",
    "device_id": "35KV_ZHUJINGKOU_YHJX",
    "SignalReset": "0",
    "P": "10.4",
    "HandcartStatus": "1",
    "Q": "-12.34",
    "TVDX": "0",
    "GL2D": "0",
    "event_time_utc": "20220620T070750Z",
    "LocalOperation": "1",
    "GL3D": "0",
    "Ia": "124.8",
    "BreakStatus": "1",
    "Ib": "0",
    "GL1D": "0",
    "Ic": "124.600006",
    "DeviceMaintenance": "0",
    "event_time": "2022-06-20 15:07:50",
    "SprChargStatus": "0"
  }
}


 

3.读取并解析json文件

 

   //1.读取文件
    DWORD len = m_infileJson.GetLength();
    char* filebuf = new char(len + 1);
    filebuf[len] = '\0';                            //终止字符串,用于输出
    m_infileJson.SeekToBegin();
    m_infileJson.Read(filebuf, sizeof(char) * len);  //缓冲区的长度
    
    //2.读取解析json    
     // 2.1 文件流入doc中
     // 2.2 遍历 读入到容器 ConstMemberIterator devit;
     // string key=(devit->name).GetString();
     // const rapidjson::Value& devvalue = devit->value;  //value根据类型解析


    Document jsondom_read;   
    char* jsondata;
    jsondata = filebuf;
    jsondom_read.Parse(jsondata);       
    if (jsondom_read.HasParseError())
    {
        printf("parse error: (%d:%d)%s\n", jsondom_read.GetParseError(), jsondom_read.GetErrorOffset(), GetParseError_En(jsondom_read.GetParseError()));
        return;
    }
    else
    {
        //3.读取数据
        Value::ConstMemberIterator devit;
        for (devit = jsondom_read.MemberBegin(); devit != jsondom_read.MemberEnd(); ++devit)
        {
            string devkey = (devit->name).GetString();  //dev key值  最外面一层
            const char* ch = devkey.c_str();
            const rapidjson::Value& devvalue = devit->value;//value
            if (devvalue.IsObject())                         //dev遍历
            {
                Value::ConstMemberIterator itemit;
                for (itemit = jsondom_read[ch].MemberBegin(); itemit != jsondom_read[ch].MemberEnd(); ++itemit)//item遍历
                {
                    string itemkey = (itemit->name).GetString();
                    const rapidjson::Value& itemvalue = itemit->value;
                    if (itemvalue.IsString())
                    {
                     
                        string stritemvalue = (itemit->value).GetString();
                       }
}
}

4.写入到json文件
 

4.1Addmember构造json->文件流

    Document jsondoc_write_addmember;        //1.构建一个document
    jsondoc_write_addmember.SetObject();

    // 2.添加    字符常量 

    const char* name = "success_url";
    const char* value = "https://www.google.com";
    jsondoc_write_addmember.AddMember(rapidjson::StringRef(name), rapidjson::StringRef(value), jsondoc_write_addmember.GetAllocator());  

    // 3.添加 json object
    rapidjson::Value info_objects(rapidjson::kObjectType);
    std::string jsonObject = "json_object";
    info_objects.AddMember(rapidjson::StringRef("class_room"), rapidjson::StringRef("NO. 6110"), jsondoc_write_addmember.GetAllocator());
    info_objects.AddMember(rapidjson::StringRef("teacher_name"), rapidjson::StringRef("ZhangSanfeng"), jsondoc_write_addmember.GetAllocator());
    jsondoc_write_addmember.AddMember(rapidjson::StringRef(jsonObject.c_str()), info_objects, jsondoc_write_addmember.GetAllocator());

    // 4.添加json array
    rapidjson::Value array_objects(rapidjson::kArrayType);
    for (int i = 0; i < 2; i++)
    {
        rapidjson::Value object(rapidjson::kObjectType);
        rapidjson::Value nobject(rapidjson::kNumberType);
        nobject.SetInt(i);
        object.AddMember(rapidjson::StringRef("id"), nobject, jsondoc_write_addmember.GetAllocator());
        object.AddMember(rapidjson::StringRef("name"), rapidjson::StringRef("zhangsan"), jsondoc_write_addmember.GetAllocator());
        array_objects.PushBack(object, jsondoc_write_addmember.GetAllocator());
    }
    char* jsonArrayName = "jsonArrayName";
    jsondoc_write_addmember.AddMember(rapidjson::StringRef(jsonArrayName), array_objects, jsondoc_write_addmember.GetAllocator());


   //5.jsondom中的buffer 转换成C++ 文件流用于存成文件
    rapidjson::StringBuffer buffer;
    rapidjson::Writer writer(buffer);
    jsondoc_write_addmember.Accept(writer);
    FILE* fp;
    fopen_s(&fp, "D:\\testdata\\out_simple_addmember.json", "w");
    if (fp)    
    {
        fputs(buffer.GetString(), fp);
        fclose(fp);
    }

4.2writer 构造json->文件流

    //1.Writer  用法:
    // StartObject();  
    //  writer.Key("hello");                
    //  writer.String("world");   
    //  writer.EndObject();


    rapidjson::StringBuffer writerbuf;
    rapidjson::Writer writer(writerbuf);

    writer.StartObject();               // Between StartObject()/EndObject(),
    writer.Key("hello");                // output a key,
    writer.String("world");             // follow by a value.
    writer.Key("t");
    writer.Bool(true);
    writer.Key("f");
    writer.Bool(false);
    writer.Key("n");
    writer.Null();
    writer.Key("i");
    writer.Uint(123);
    writer.Key("pi");
    writer.Double(3.1416);
    writer.Key("a");
    writer.StartArray();                
    for (unsigned i = 0; i < 4; i++)
        writer.Uint(i);                 
    writer.EndArray();
    writer.EndObject();


    writerbuf.GetString();                  //数据内容放在  writerbuf中 文件流

    FILE* fp;
    fopen_s(&fp, "D:\\testdata\\out_simple_writer.json", "w");
    if (fp)
    {
        fputs(writerbuf.GetString(), fp);
        fclose(fp);
    }


 

 4.3 writer 支持的类型

  

 writer.StartObject();
    //1. 整数类型
    writer.Key("Int");
    writer.Int(1);

    //2. 浮点类型
    writer.Key("Double");
    writer.Double(12.0000001);

    //3. 字符串类型
    writer.Key("String");
    writer.String("This is a string");

    //4. 结构体类型
    writer.Key("Object");
    writer.StartObject();
    writer.Key("name");
    writer.String("qq849635649");
    writer.Key("age");
    writer.Int(25);
    writer.EndObject();

    //5. 数组类型
    //5.1 整型数组
    writer.Key("IntArray");
    writer.StartArray();
    //顺序写入即可
    writer.Int(10);
    writer.Int(20);
    writer.Int(30);
    writer.EndArray();

    //5.2 浮点型数组
    writer.Key("DoubleArray");
    writer.StartArray();
    for (int i = 1; i < 4; i++)
    {
        writer.Double(i * 1.0);
    }
    writer.EndArray();

    //5.3 字符串数组
    writer.Key("StringArray");
    writer.StartArray();
    writer.String("one");
    writer.String("two");
    writer.String("three");
    writer.EndArray();

    //5.4 混合型数组
    //这说明了,一个json数组内容是不限制类型的
    writer.Key("MixedArray");
    writer.StartArray();
    writer.String("one");
    writer.Int(50);
    writer.Bool(false);
    writer.Double(12.005);
    writer.EndArray();

    //5.5 结构体数组
    writer.Key("People");
    writer.StartArray();
    for (int i = 0; i < 3; i++)
    {
        writer.StartObject();
        writer.Key("name");
        writer.String("qq849635649");
        writer.Key("age");
        writer.Int(i * 10);
        writer.Key("sex");
        writer.Bool((i % 2) == 0);
        writer.EndObject();
    }
    writer.EndArray();

    writer.EndObject();
  


    

5.C++中string、char *、char[]、const char*的转换

1) char*转string:可以直接赋值。
2) char[]转string:可以直接赋值。
3) char*转char[]:不能直接赋值,可以循环char*字符串逐个字符赋值,也可以使用strcpy_s等函数。
4) string转char[]:不能直接赋值,可以循环char*字符串逐个字符赋值,也可以使用strcpy_s等函数
5) string转char*:调用string对象的c_str函数或data函数或copy函数。
6) char[]转char*:直接赋值即可。

使用时,要对源格式和目标格式进行初始化。源格式赋值为具体的内容,目标格式赋值为空。


c++-json(0)-rapidjson-read-write-实例代码_第1张图片

你可能感兴趣的:(c++,json,开发语言)