jsoncpp空對象添加以及兩種不同格式的轉換

#include "json/json.h"
#include <iostream>

/** \brief Write a Value object to a string.
 * Example Usage:
 * $g++ stringWrite.cpp -ljsoncpp -std=c++11 -o stringWrite
 * $./stringWrite
 * {
 *     "action" : "run",
 *     "data" :
 *     {
 *         "number" : 1
 *     }
 * }
 */

#define __STRING(x)	#x
int test1() {
  Json::Value root;
  Json::Value data;
  Json::Value array= Json::objectValue;

  constexpr bool shouldUseOldWay = false;
  root["action"] = "run";
  data["number"] = 1;
  root["data"] = data;
  root["params"].append("abcddd");
  root["params"].append("pgmm");
  root["params"].append(Json::objectValue);
  //root.append(array);
  std::cout<<"hello world !"<<std::endl;

  if (shouldUseOldWay) {
    Json::FastWriter writer;
    const std::string json_file = writer.write(root);
    std::cout << json_file << std::endl;
  } else {
    Json::StreamWriterBuilder builder;
    const std::string json_file = Json::writeString(builder, root);
    std::cout << json_file << std::endl;
  }
    std::cout<<"hello world !"<<std::endl;
  return EXIT_SUCCESS;
}


int main(){
    Json::Value root;
    Json::Value subValue;
    root["jsonrpc"]="2.0";
    root["id"]=98;
    root["method"]="call";
    root["params"].append("00000000000000000000000000000000000000");
    root["params"].append("kpalive");
    root["params"].append("status");
    root["params"].append(Json::objectValue);

    subValue["config"]="pgmm";
    subValue["section"]="pgmmconfig";
    subValue["cid"] ="1";
    root["params"].append(subValue);
    Json::StreamWriterBuilder builder;
    const std::string json_file = Json::writeString(builder, root);
    std::cout << json_file << std::endl;
    return 0;
}

打印結果:

{
	"id" : 98,
	"jsonrpc" : "2.0",
	"method" : "call",
	"params" : 
	[
		"00000000000000000000000000000000000000",
		"kpalive",
		"status",
		{},
		{
			"cid" : "1",
			"config" : "pgmm",
			"section" : "pgmmconfig"
		}
	]
}
Press <RETURN> to close this window...

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章