json为JavaScript object notation 是一种数据格式,逐渐替换掉了传统的xml 。json数据格式的属性名称和字符串值需要用双引号引起来,用单引号或者不用引号会导致读取数据错误。json的另外一个数据格式是数组,和javascript中的数组字面量相同。
使用Json的格式与解析方便的可以表示一个对象信息,json有两种格式:
json中不能有注释,undefined,只要涉及到字符串的就必须双引号
①对象格式:{"key1":obj,"key2":obj,"key3":obj...}、
②数组/集合格式:[obj,obj,obj...]。
json.parse()解析将字符串解析成对应的值,
例子:
将nlohmann/json: JSON for Modern C++ (github.com)
中代码下载下来,然后将include文件夹添加到测试工程的包含路径下即可:
我是用的绝对路径:D:\excer\mfc\json\json\include\;
测试代码:
#include <iostream>
#include <fstream>
#include <ostream>
#include "json.hpp"
using json = nlohmann::json;
int main()
{
std::cout << "Hello World!\n";
//读取json文件--------------------------------
std::ifstream f("example.json");
json data = json::parse(f);
double pi = data["pi"];
bool td = false;
//td = data["happy"];
if (!data["happy"].is_null())
{
td = data["happy"];
}
std::string sname = data["name"].get<std::string>(); ;
std::cout << data;
int c = 0;
//输出json文件--------------------------------
// create an empty structure (null)
json j;
//方式一---------------------------------------
// add a number that is stored as double (note the implicit conversion of j to an object)
j["pi"] = 3.141;
// add a Boolean that is stored as bool
j["happy"] = true;
// add a string that is stored as std::string
j["name"] = "Niels";
// add another null object by passing nullptr
j["nothing"] = nullptr;
// add an object inside the object
j["answer"]["everything"] = 42;
// add an array that is stored as std::vector (using an initializer list)
j["list"] = { 1, 0, 2 };
// add another object (using an initializer list of pairs)
j["object"] = { {"currency", "USD"}, {"value", 42.99} };
//方式二---------------------------------------
// instead, you could also write (which looks very similar to the JSON above)
json j2 = {
{"pi", 3.141},
{"happy", true},
{"name", "Niels"},
{"nothing", nullptr},
{"answer", {
{"everything", 42}
}},
{"list", {1, 0, 2}},
{"object", {
{"currency", "USD"},
{"value", 42.99}
}}
};
//输出到文件中
std::ofstream fout("out.json");
fout << std::setw(4)<< j;
fout << std::setw(4) << j2;
fout.close();
}
对应的:json格式
{
"pi": 3.141,
"happy": true,
"name": "Niels",
"nothing": null,
"answer": {
"everything": 42
},
"list": [1, 0, 2],
"object": {
"currency": "USD",
"value": 42.99
}
}
异常处理:
标签(关键字)happy2不存在,只有标签(关键字)happy,如果执行该语句bool td = data["happy2"]; 在直接读取标签happy2则解析器会崩溃。
解决办法:下面先对标签判断一下是否为空,为空的话,就不要直接读取了。 标签不为空才能直接读取
//td = data["happy"];
if (!data["happy"].is_null())//关键字不为空才能直接读取
{
td = data["happy"];
}
主要看下面的文章:
写json格式
c++中nlohmann json的基本使用教程_C 语言_脚本之家 (jb51.net)
nlohmann/json: JSON for Modern C++ (github.com)https://github.com/nlohmann/json/tree/develop
JSON的三种格式https://blog.csdn.net/daxiong0816/article/details/125132404
json格式 (keoaeic.org)https://mip.keoaeic.org/unscramble_major/4394.htmlC++ json格式的书写_雪星途的博客-CSDN博客https://blog.csdn.net/weixin_45387966/article/details/122469835