rapidjson write & read

前端之家收集整理的这篇文章主要介绍了rapidjson write & read前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

目标json:

{
  "result" : 1,"data" : {
    "friends" : [
      {
        "Award" : 2,"friend" : {
          "gate" : 0,"nickName" : "游客111111","uuid" : "111111"
        }
      }
    ],"invited" : true
  }
}

rapidjson code:

#include "rapidjson.h"
#include "stringbuffer.h"
#include "writer.h"
using namespace rapidjson;

    Document doc;
    doc.SetObject();
    Document::AllocatorType& all = doc.GetAllocator();
    doc.AddMember("result",1,all);
        Value data;
        data.SetObject();
            Value friends(kArrayType);
            for (int i = 0; i < 1; i++) {
                Value friendsData;
                friendsData.SetObject();
                friendsData.AddMember("Award",2,all);
                        Value friendData;
                        friendData.SetObject();
                        friendData.AddMember("gate",all);
                        friendData.AddMember("uuid","111111",all);
                        friendData.AddMember("nickName","游客111111",all);
                friendsData.AddMember("friend",friendData,all);
                friends.PushBack(friendsData,all);
            }
        data.AddMember("friends",friends,all);
        data.AddMember("invited",true,all);
    doc.AddMember("data",data,all);
    rapidjson::StringBuffer buffer;
    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
    doc.Accept(writer);
    std::string dataString = buffer.GetString();


解析目标json:


    Document jsonDic;
    string str = "目标JSON";
    CommonFuncDefine::parseString(str,jsonDic);
    Value &dataValue= jsonDic["data"];
    int isInvited = dataValue["invited"].GetBool();
    
    Value &friendsData = dataValue["friends"];
    if (friendsData.IsArray()) {
        for (rapidjson::SizeType i = 0; i < friendsData.Size(); i++)
        {
            Value &friendData = friendsData[i];
            int invitedAward = friendData["Award"].GetInt();
            Value &friendObject = friendData["friend"];
            int tollgate = friendObject["gate"].GetInt();
            string uuid = friendObject["uuid"].GetString();
            string nickName = friendObject["nickName"].GetString();
        }
    }
原文链接:https://www.f2er.com/json/289960.html

猜你在找的Json相关文章