Jsoncpp: 所見即所得使用範例

jsoncpp版本: jsoncpp-1.8.4ios

基本操做

#include <json/json.h>

int main() {
  Json::Value root;
  
  root["key1"] = 1;
  root["key2"] = "good";
  root["indent"]["length"] = 2;
  root["indent"]["use_space"] = true;

  Json::Value v(Json::arrayValue);
  v[0] = "clojure";
  v[1] = "json";
  v[2] = "xml";
  root["key3"] = v;
  return 0;
}
複製代碼

遍歷與類型

for (auto i = root.begin(); i != root.end(); i++) {
    Json::Value& obj = *i;
    const std::string name = i.name();
    std::cout << name << "-" << i.key() << ": " << obj.isArray() << "\n";
  }
複製代碼

讀入

Json::Value root;
  std::ifstream infile;
  infile.open("your.json", std::ios::in);
  try {
    infile >> root;
  } catch (std::exception& e) {
    root = Json::objectValue;
  }
  infile.close();
複製代碼

這裏用的是文件的讀入流, 也能夠是文本的stringstreamjson

寫出

std::ofstream of;
  of.open("your.json", std::ios::out);
  of << root << std::endl;
  of.flush();
  of.close();
複製代碼

格式化輸出

默認輸出的json縮進是\t, 若是要改爲2個空格:bash

Json::StreamWriterBuilder builder;
  builder["indentation"] = " ";
  builder.newStreamWriter()->write(root, &std::cout);
複製代碼

這裏有個讓人費解的地方: void StreamWriterBuilder::setDefaults(Json::Value* settings)看起來彷佛是讓一個settings對象成爲StreamWriterBuilder全局默認的配置, 但實際上只是讓一個配置重置成'默認'數據, 真是莫名其妙的用法...ui

void StreamWriterBuilder::setDefaults(Json::Value* settings) {
  //! [StreamWriterBuilderDefaults]
  (*settings)["commentStyle"] = "All";
  (*settings)["indentation"] = "\t";
  (*settings)["enableYAMLCompatibility"] = false;
  (*settings)["dropNullPlaceholders"] = false;
  (*settings)["useSpecialFloats"] = false;
  (*settings)["precision"] = 17;
  (*settings)["precisionType"] = "significant";
  //! [StreamWriterBuilderDefaults]
}
複製代碼
相關文章
相關標籤/搜索