Jsoncpp: 所见即所得使用范例

jsoncpp版本: jsoncpp-1.8.4

基本操作

#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();

这里用的是文件的读入流, 也可以是文本的stringstream

写出

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

格式化输出

默认输出的json缩进是\t, 如果要改成2个空格:

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

这里有个让人费解的地方:
void StreamWriterBuilder::setDefaults(Json::Value* settings)看起来似乎是让一个settings对象成为StreamWriterBuilder全局默认的配置, 但实际上只是让一个配置重置成'默认'数据, 真是莫名其妙的用法...

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]
}

推荐阅读更多精彩内容