jsoncons使用之: 构造json

默认的json构造函数产生一个空的json对象。 例如

jsoncons::json image_sizing;
std::cout << image_sizing << std::endl;
//输出{}

要使用成员构造一个json对象,需要获取一个空的json对象并设置一些“名称/值”对

image_sizing.insert_or_assign("Resize To Fit",true);  // a boolean 
image_sizing.insert_or_assign("Resize Unit", "pixels");  // a string
image_sizing.insert_or_assign("Resize What", "long_edge");  // a string
image_sizing.insert_or_assign("Dimension 1",9.84);  // a double
image_sizing.insert_or_assign("Dimension 2",json::null());  // a null value

 或者,使用对象初始化列表

jsoncons::json file_settings(json::object_arg, {
	{"Image Format", "JPEG"},
	{"Color Space", "sRGB"},
	{"Limit File Size", true},
	{"Limit File Size To", 10000}
		});

要构造json数组,需要使用数组类型初始化 ,并添加一些元素

jsoncons::json color_spaces(json_array_arg);
color_spaces.push_back("sRGB");
color_spaces.push_back("AdobeRGB");
color_spaces.push_back("ProPhoto RGB");

或者使用数组初始化列表

jsoncons::json image_formats(json_array_arg, {"JPEG","PSD","TIFF","DNG"});

运算符[]提供了另一种设置名称-值对的方法。 

jsoncons::json file_export;
file_export["File Format Options"]["Color Spaces"] = std::move(color_spaces);
file_export["File Format Options"]["Image Formats"] = std::move(image_formats);
file_export["File Settings"] = std::move(file_settings);
file_export["Image Sizing"] = std::move(image_sizing);

//如果file_export[“file Format Options”]不存在,则file_export["File Format Options"]["Color Spaces"] = std::move(color_spaces);语句将创建“file Format Options”作为对象,并将“Color Spaces”放入其中。

std::cout << pretty_print(file_export) << std::endl;

 输出:

{
    "File Format Options": {
        "Color Spaces": ["sRGB","AdobeRGB","ProPhoto RGB"],
        "Image Formats": ["JPEG","PSD","TIFF","DNG"]
    },
    "File Settings": {
        "Color Space": "sRGB",
        "Image Format": "JPEG",
        "Limit File Size": true,
        "Limit File Size To": 10000
    },
    "Image Sizing": {
        "Dimension 1": 9.84,
        "Dimension 2": null,
        "Resize To Fit": true,
        "Resize Unit": "pixels",
        "Resize What": "long_edge"
    }
}

文章来源 jsoncons官方github: https://danielaparker.github.io/jsoncons/

猜你喜欢

转载自blog.csdn.net/weixin_44843859/article/details/109334317
今日推荐