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]
}
复制代码
相关文章
相关标签/搜索