C++ 读写JSON

用Rapid Json

参考:http://rapidjson.org/zh-cn/

RapidJSON是腾讯开源的一个高效的C++ JSON解析器及生成器,它是只有头文件的C++库。RapidJSON是跨平台的,支持Windows, Linux, Mac OS X及iOS, Android。

库:链接:https://pan.baidu.com/s/1tfKOotRbsh5PIKZeDgZfZA
提取码:wlg6

1. 生成json

////////////// 生成JSON //////////////
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <iostream>

int _tmain(int argc, _TCHAR* argv[])
{
    rapidjson::StringBuffer buf;
    rapidjson::Writer<rapidjson::StringBuffer> writer(buf);
    //rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buf); // it can word wrap

    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();                // Between StartArray()/EndArray(),
    for (unsigned i = 0; i < 4; i++)
        writer.Uint(i);                 // all values are elements of the array.
    writer.EndArray();
    writer.EndObject();
    // {"hello":"world","t":true,"f":false,"n":null,"i":123,"pi":3.1416,"a":[0,1,2,3]}
    */
    
    writer.Key("country"); writer.String("中国");
    writer.Key("province");
    writer.StartArray();
    writer.StartObject();
    writer.Key("name"); writer.String("黑龙江");
    writer.Key("cities"); writer.StartArray(); writer.String("哈尔滨"); writer.String("大庆"); writer.EndArray();
    writer.EndObject();
    writer.StartObject();
    writer.Key("name"); writer.String("广东");
    writer.Key("cities"); writer.StartArray(); writer.String("广州"); writer.String("深圳"); writer.String("珠海"); writer.EndArray();
    writer.EndObject();
    writer.EndArray();

    writer.EndObject();

    const char* s = buf.GetString();//"{"country":"中国","province":[{"name":"黑龙江","cities":["哈尔滨","大庆"]},{"name":"广东","cities":["广州","深圳","珠海"]}]}"
    std::cout << s << "\n";
    return 0;
}
View Code

2. 解析json

////////////////// 解析 JSON  ///////////////////////////
#include <iostream>
#include <string>
#include "rapidjson/document.h"

/*
{
  "country": "中国",
  "province": [
    {
      "name": "黑龙江",
      "cities": ["哈尔滨","大庆"]
    },
    {
      "name": "广东",
      "cities": ["广州","深圳","珠海"]
    },
    {
      "name": "台湾",
      "cities": ["台北","高雄"]
    },
    {
      "name": "新疆",
      "cities": ["乌鲁木齐"]
    }
  ]
}
*/
int _tmain(int argc, _TCHAR* argv[])
{
    const char* str = "{\"country\":\"中国\",\"province\":[{\"name\":\"黑龙江\",\"cities\":[\"哈尔滨\",\"大庆\"]},{\"name\":\"广东\",\"cities\":[\"广州\",\"深圳\",\"珠海\"]},{\"name\":\"台湾\",\"cities\":[\"台北\",\"高雄\"]},{\"name\":\"新疆\",\"cities\":[\"乌鲁木齐\"]}]}";
    rapidjson::Document document;
    document.Parse(str);
    assert(document.IsObject());
    std::string s = document["country"].GetString();
    
    const rapidjson::Value& a = document["province"];
    assert(a.IsArray());
    for (rapidjson::SizeType i = 0; i < a.Size(); i++) // 使用 SizeType 而不是 size_t
    {
        const rapidjson::Value& b = a[i];
        assert(b.IsObject());
        std::string provinceName = b["name"].GetString();
        std::cout << provinceName << ": ";
        const rapidjson::Value& c = b["cities"];
        assert(c.IsArray());
        for (rapidjson::SizeType i = 0; i < c.Size(); i++)
        {
            std::string cityName = c[i].GetString();
            std::cout << cityName << " ";
        }
        std::cout << "\n";
    }
    return 0;
}
View Code

网上的例子:

#include <iostream>
#include <string>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"

using namespace rapidjson;
using namespace std;

string readfile(const char *filename){
    FILE *fp = fopen(filename, "rb");
    if(!fp){
        printf("open failed! file: %s", filename);
        return "";
    }
    
    char *buf = new char[1024*16];
    int n = fread(buf, 1, 1024*16, fp);
    fclose(fp);
    
    string result;
    if(n>=0){
        result.append(buf, 0, n);
    }
    delete []buf;
    return result;
}

int parseJSON(const char *jsonstr){
    Document d;
    if(d.Parse(jsonstr).HasParseError()){
        printf("parse error!\n");
        return -1;
    }
    if(!d.IsObject()){
        printf("should be an object!\n");
        return -1;
    }
    if(d.HasMember("errorCode")){
        Value &m = d["errorCode"];
        int v = m.GetInt();
        printf("errorCode: %d\n", v);
    }
    printf("show numbers: \n");
    if(d.HasMember("numbers")){
        Value &m = d["numbers"];
        if(m.IsArray()){
            for(int i = 0; i < m.Size(); i++){
                Value &e = m[i];
                int n = e.GetInt();
                printf("%d,", n);
            }
        }
    }
    return 0;
}

int parseJSON2(const char *jsonstr){
    Document d;
    if(d.Parse(jsonstr).HasParseError()){
        throw string("parse error!\n");
    }
    if(!d.IsObject()){
        throw string("should be an object!\n");
    }
    if(!d.HasMember("errorCode")){
        throw string("'errorCode' no found!");
    }
    
    Value &m = d["errorCode"];
    int v = m.GetInt();
    printf("errorCode: %d\n", v);
    printf("show numbers:\n");
    if(d.HasMember("numbers")){
        Value &m = d["numbers"];
        if(m.IsArray()){
            for(int i = 0; i < m.Size(); i++){
                Value &e = m[i];
                int n = e.GetInt();
                printf("%d", n);
            }
        }
    }
    return 0;
}

/*
 //path="/Users/macname/Desktop/example.json"
 
 {
 "errorCode":0,
 "reason":"OK",
 "result":{"userId":10086,"name":"中国移动"},
 "numbers":[110,120,119,911]
 }
 
 */
int main(){
    
    string jsonstr = readfile("/Users/macname/Desktop/example.json");
    //parseJSON(jsonstr.c_str());
    
    try{
        parseJSON2(jsonstr.c_str());
    }catch(string e){
        printf("error: %s \n", e.c_str());
    }
    getchar();
    return 0;
}

输出

errorCode: 0
show numbers:
110120119911
View Code

 

使用JSONCpp库

参考:Cpp Library 之 JsonCpp

 

例子

*******

 

posted @ 2022-03-20 18:01  htj10  阅读(365)  评论(0编辑  收藏  举报
TOP