java multimap 序列化_C++ JSON库的使用

1. 如何使用?

2. 常用方法

2.1 创建json对象

2.1.1 使用cin,cout输入输出流

2.1.2 提供根据键直接生成键值对的方法

2.1.3 json::array json::object

2.1.4 几个区别

2.2 序列化

2.2.1 标准输出自动序列化

2.2.2 使用dump()函数

2.3 反序列化

2.3.1 从标准输入反序列化

2.3.2 通过附加_json到字符串文字来创建对象实现反序列化

2.3.3 使用json::parse()函数

2.3.4 从迭代器范围读取

2.3 与STL适应

2.4 STl与json转换

2.5 json最重要的还是设计config文件

最后

JSON(Java Object Notation) 是一种轻量级的数据交换格式。它基于ECMA的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C、C++、C#、Java、Java、Perl、Python等)。这些特性使JSON成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成(一般用于提升网络传输速率)。

今天介绍的json版本是在c++下使用的,是一个开源项目。

GitHub开源项的地址:https://github.com/nlohmann/json

json for modern c++是一个德国大牛nlohmann写的,该版本的json有以下特点:

1.直观的语法。

2.整个代码由一个头文件组成json.hpp,没有子项目,没有依赖关系,没有复杂的构建系统,使用起来非常方便。

3.使用c++11标准编写。

4.使用json 像使用STL容器一样。

5.STL和json容器之间可以相互转换。

1. 如何使用?

将github上的src文件夹里的json.hpp头文件下载保存到当前目录中。

在代码中包含json.hpp头文件并引入json作用域

#include "json.hpp"

using json = nlohmann::json;

1

2

2. 常用方法

2.1 创建json对象

2.1.1 使用cin,cout输入输出流

json提供了cin,cout的输入输出流的操作符。但需要注意的是,cin要有ctr + D结束输入。cout会自动把json转换为string。

#include

#include "json.hpp"

using json = nlohmann::json;

using std::cout;

using std::endl;

using std::cin;

int main(int argc, const char * argv[]) {

json temp;

cin >> temp;

cout << temp << endl;

return 0;

}

/*

输入:

{

"pi": 3.141,

"happy": true,

"name": "Niels",

"nothing": null,

"answer": {

"everything": 42

},

"list": [1, 0, 2],

"object": {

"currency": "USD",

"value": 42.99

}

}

{"answer":{"everything":42},"happy":true,"list":[1,0,2],"name":"Niels","nothing":null,"object":{"currency":"USD","value":42.99},"pi":3.141}

Program ended with exit code: 0

*/

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

2.1.2 提供根据键直接生成键值对的方法

#include

#include "json.hpp"

using json = nlohmann::json;

using std::cout;

using std::endl;

using std::cin;

int main(int argc, const char * argv[]) {

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

}}

};

cout << j << endl;

cout << endl;

cout << j2 << endl;

return 0;

}

/*

{"answer":{"everything":42},"happy":true,"list":[1,0,2],"name":"Niels","nothing":null,"object":{"currency":"USD","value":42.99},"pi":3.141}

{"answer":{"everything":42},"happy":true,"list":[1,0,2],"name":"Niels","nothing":null,"object":{"currency":"USD","value":42.99},"pi":3.141}

Program ended with exit code: 0

*/

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

2.1.3 json::array json::object

在所有上述情况下,你不需要“告诉”编译器要使用哪个JSON值。如果你想明确或表达一些边缘的情况下,可以使用json::array,json::object。

#include

#include "json.hpp"

using json = nlohmann::json;

using std::cout;

using std::endl;

using std::cin;

int main(int argc, const char * argv[]) {

// a way to express the empty array []

json empty_array_explicit = json::array();

// ways to express the empty object {}

json empty_object_implicit = json({});

json empty_object_explicit = json::object();

// a way to express an _array_ of key/value pairs [["currency", "USD"], ["value", 42.99]]

json array_not_object = { json::array({"currency", "USD"}), json::array({"value", 42.99}) };

for (auto object : array_not_object) {

cout << object << endl;

}

return 0;

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

2.1.4 几个区别

array是一个数组,可以用数字直接下标访问。

json array = {

"yan",12,"ze",13

};

cout << array[0] << endl;

1

2

3

4

array是一个数组里面放了一个数组。认为”yan”,12是数组里面的两个元素。

json array = {

{"yan",12},

"ze",13

};

cout << array[0][0] << endl;

1

2

3

4

5

array是数组里面有一个数组(里面包含了一个键值对)。

json array = {

{{"yan",12}},

"ze",13

};

cout << array[0]["yan"] << endl;

1

2

3

4

5

array里面含有两个键值对。

json array = {

{"yan",12},

{"ze",13}

};

cout << array["yan"] << endl;

1

2

3

4

5

array里面含有两个数组,数组里面分别有一个键值对。

json array = {

{

{"yan",12}

},

{

{"ze",13}

}

};

cout << array[0]["yan"] << endl;

1

2

3

4

5

6

7

8

9

(注意区分{}的位置来判断对象的性质)。

如果实在判断不出来,可以用C++11的for语句,看每一个输出结果的符号来判断每一个对象的性质。

2.2 序列化

将json对象序列化,成为字符串

2.2.1 标准输出自动序列化

json j

std :: cout << j;

// setw操纵器被重载以设置漂亮打印的缩进

std :: cout << std :: setw( 4)<< j << std :: endl;

1

2

3

4

2.2.2 使用dump()函数

//显式转换为string

std::string s = j.dump(); // {\"happy\":true,\"pi\":3.141}

//序列化与漂亮的打印

//传入空格的数量缩进

std::cout << j.dump(4) << std::endl;

// 输出:

//{

// "happy": true,

// "pi": 3.141

// }

1

2

3

4

5

6

7

8

9

10

11

2.3 反序列化

将数据流转化为json对象

2.3.1 从标准输入反序列化

json j

std :: cin >> j;

1

2

2.3.2 通过附加_json到字符串文字来创建对象实现反序列化

//从字符串文字创建对象

json j = " { \" happy \":true,\" pi \":3.141} " _json;

//或者原始字符串文字

auto j2 = R"(

{

"happy":true,

"pi":3.141

}

)" _json;

1

2

3

4

5

6

7

8

9

10

请注意,没有附加_json后缀,传递的字符串文字不会被解析,而只是用作JSON字符串值。也就是说,json j = "{ “happy”: true, “pi”: 3.141 }“只存储字符串”{ “happy”: true, “pi”: 3.141 }"而不是解析实际的对象。

2.3.3 使用json::parse()函数

//明确解析

auto j3 = json::parse(" { \" happy \":true,\" pi \":3.141} ");

1

2

2.3.4 从迭代器范围读取

您还可以从迭代器范围读取JSON; 也就是说,可以从其内容存储为连续字节序列的迭代器访问的任何容器,例如std::vector

std :: vector < uint8_t > v = { ' t ',' r ',' u ',' e ' };

json j = json :: parse(v.begin(),v.end());

//或

std :: vector < uint8_t > v = { ' t ',' r ',' u ',' e ' };

json j = json :: parse(v);

1

2

3

4

5

6

2.3 与STL适应

json提供了许多和STL类似的操作方法:

#include

#include "json.hpp"

using json = nlohmann::json;

using std::cout;

using std::endl;

using std::cin;

int main(int argc, const char * argv[]) {

// create an array using push_back

json j;

j.push_back("foo");

j.push_back(1);

j.push_back(true);

// iterate the array

for (json::iterator it = j.begin(); it != j.end(); ++it) {

std::cout << *it << '\n';

}

// range-based for

for (auto element : j) {

std::cout << element << '\n';

}

// getter/setter

const std::string tmp = j[0];

j[1] = 42;

bool foo = j.at(2);

// other stuff

j.size(); // 3 entries

j.empty(); // false

j.type(); // json::value_t::array

j.clear(); // the array is empty again

// convenience type checkers

j.is_null();

j.is_boolean();

j.is_number();

j.is_object();

j.is_array();

j.is_string();

// comparison

cout << (j == "[\"foo\", 1, true]"_json) << endl; // true

// create an object

json o;

o["foo"] = 23;

o["bar"] = false;

o["baz"] = 3.141;

// special iterator member functions for objects

for (json::iterator it = o.begin(); it != o.end(); ++it) {

std::cout << it.key() << " : " << it.value() << "\n";

}

// find an entry

if (o.find("foo") != o.end()) {

// there is an entry with key "foo"

cout << *o.find("foo") << endl;

}

// or simpler using count()

int foo_present = o.count("foo"); // 1

int fob_present = o.count("fob"); // 0

cout << foo_present << endl;

cout << fob_present << endl;

// delete an entry

o.erase("foo");

cout << (o.find("foo") == o.end()) << endl;

return 0;

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

2.4 STl与json转换

允许把STL与json相转换。

#include

#include

#include

#include

#include

#include

#include "json.hpp"

using json = nlohmann::json;

using std::cout;

using std::endl;

using std::cin;

int main(int argc, const char * argv[]) {

std::vector c_vector {1, 2, 3, 4};

json j_vec(c_vector);

// [1, 2, 3, 4]

std::deque c_deque {1.2, 2.3, 3.4, 5.6};

json j_deque(c_deque);

// [1.2, 2.3, 3.4, 5.6]

std::list c_list {true, true, false, true};

json j_list(c_list);

// [true, true, false, true]

std::forward_list c_flist {12345678909876, 23456789098765, 34567890987654, 45678909876543};

json j_flist(c_flist);

// [12345678909876, 23456789098765, 34567890987654, 45678909876543]

std::array c_array {{1, 2, 3, 4}};

json j_array(c_array);

// [1, 2, 3, 4]

std::set<:string> c_set {"one", "two", "three", "four", "one"};

json j_set(c_set); // only one entry for "one" is used

// ["four", "one", "three", "two"]

std::unordered_set<:string> c_uset {"one", "two", "three", "four", "one"};

json j_uset(c_uset); // only one entry for "one" is used

// maybe ["two", "three", "four", "one"]

std::multiset<:string> c_mset {"one", "two", "one", "four"};

json j_mset(c_mset); // only one entry for "one" is used

// maybe ["one", "two", "four"]

std::unordered_multiset<:string> c_umset {"one", "two", "one", "four"};

json j_umset(c_umset); // both entries for "one" are used

// maybe ["one", "two", "one", "four"]

return 0;

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

对于关联容器,json直接把map中的键值对转化为json的object。

std::map<:string int> c_map { {"one", 1}, {"two", 2}, {"three", 3} };

json j_map(c_map);

// {"one": 1, "three": 3, "two": 2 }

std::unordered_map c_umap { {"one", 1.2}, {"two", 2.3}, {"three", 3.4} };

json j_umap(c_umap);

// {"one": 1.2, "two": 2.3, "three": 3.4}

std::multimap<:string bool> c_mmap { {"one", true}, {"two", true}, {"three", false}, {"three", true} };

json j_mmap(c_mmap); // only one entry for key "three" is used

// maybe {"one": true, "two": true, "three": true}

std::unordered_multimap<:string bool> c_ummap { {"one", true}, {"two", true}, {"three", false}, {"three", true} };

json j_ummap(c_ummap); // only one entry for key "three" is used

// maybe {"one": true, "two": true, "three": true}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

json还提供隐式类型转换。

/// strings

std::string s1 = "Hello, world!";

json js = s1;

std::string s2 = js;

// Booleans

bool b1 = true;

json jb = b1;

bool b2 = jb;

// numbers

int i = 42;

json jn = i;

double f = jn;

// etc.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

也可以使用显式类型转换。

std::string vs = js.get<:string>();

bool vb = jb.get();

int vi = jn.get();

// etc.

1

2

3

4

2.5 json最重要的还是设计config文件

例如以下:

json question = {

{"question",{

{

{"id",0},

{"choice_type","single"},

{"grading",{

{"max_grade",10},

{"half_grade",5}

}},

{"standard_answer",{1}},

{"deion","this is a test for choice judger"},

{"choice",{

{

{"id",0},

{"deion","nope"}

},

{

{"id",1},

{"deion","B"}

},

{

{"id",2},

{"descrition","C"}

},

{

{"id",3},

{"deion","D"}

}

}

}

},

{

{"id",1},

{"choice_type","double"},

{"grading",{

{"max_grade",10},

{"half_grade",5}

}},

{"standard_answer",{1, 2}},

{"deion","this is a test for choice judger"},

{"choice",{

{

{"id",0},

{"deion","nope"}

},

{

{"id",1},

{"deion","B"}

},

{

{"id",2},

{"descrition","C"}

},

{

{"id",3},

{"deion","D"}

}

}

}

},

{

{"id",2},

{"choice_type","multi"},

{"grading",{

{"max_grade",10},

{"half_grade",5}

}},

{"standard_answer",{1,2}},

{"deion","this is a test for choice judger"},

{"choice",{

{

{"id",0},

{"deion","nope"}

},

{

{"id",1},

{"deion","B"}

},

{

{"id",2},

{"descrition","C"}

},

{

{"id",3},

{"deion","D"}

}

}

}

}

}

},

{"deion","this is choice questions!"}

};

json answer = {

{

{"question_id",1},

{"choice_id",{1}}

},

{

{"question_id",0},

{"choice_id",{1}}

},

{

{"question_id",2},

{"choice_id",{1,2,3}}

}

};

---------------------

作者:AI图哥

原文:https://blog.csdn.net/sinat_24143931/article/details/84974154

版权声明:本文为博主原创文章,转载请附上博文链接!

c9d93a9893f15480a105b3861c0139c1.png

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/428470.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【Excle数据透透视表】如何删除数据透视表

选中区域A4:C17,在键盘上按DELETE键删除&#xff0c;结果提示&#xff1a;那么如何删除呢&#xff1f;解决方案选中整个数透视表&#xff0c;再删除具体操作&#xff1a;选中整个数据透视表→DELETE注意&#xff1a;删除之后&#xff0c;源数据不会受到影响转载于:https://www.…

java 启动redis服务器_docker启动redis并使用java连接

一、先查找镜像docker search redis二、拉取镜像docker pull redis三、等待拉取完毕四、查看拉去的镜像docker iamges五、运行redis连接1&#xff1a;https://blog.csdn.net/weixin_38956287/article/details/80423607连接2&#xff1a;http://www.runoob.com/docker/docker-in…

【算法学习】整体二分

我们开门见山&#xff0c;讲讲一道sb题&#xff1a; 给你一个数组&#xff0c;查这个数组的第x大元素。 排序&#xff1f;可以 二分&#xff1f;怎么做啊&#xff1f; 二分出一个mid&#xff0c;判断这个数组中有多少个数小于等于mid&#xff0c;如果个数大于等于x&#xff0c;…

mysql leave的作用_MySQL数据库中DELIMITER的作用

以下的文章主要是向大家描述的是MySQL数据库中delimiter的作用是什么?我们一般都认为这个命令和存储过程关系不大&#xff0c;到底是不是这样的呢&#xff1f;以下的文章将会给你相关的知识&#xff0c;望你会有所收获。下面是一个存储过程的实例&#xff1a;DELIMITER $$USE …

Fullpage参数说明

参数说明 $(document).ready(function() {$(#fullpage).fullpage({//Navigationmenu: false,//绑定菜单&#xff0c;设定的相关属性与anchors的值对应后&#xff0c;菜单可以控制滚动&#xff0c;默认为false。anchors:[firstPage, secondPage],//anchors定义锚链接&#xff0c…

mysql100个优化技巧_完整篇:100+个MySQL调试和优化技巧(2)

▼MySQL模式优化51.检查和经常优化表.52. 经常重写InnoDB表优化.53. 有时&#xff0c;当添加列时删除索引&#xff0c;然后在添加回来索引&#xff0c;这样就会更快.54. 针对不同的需求&#xff0c;使用不同的存储引擎.55. 使用归档存储引擎日志表或审计表-这是更有效地写道.56…

Java Swing

编辑中... 转载于:https://www.cnblogs.com/startup-try/p/8040625.html

包装类java_Java 包装类

也叫过滤流类处理刘类没有对应到任何具体的流设备&#xff0c;需要给它传递一个对应的具体流设备的输出/输入流对象I/0内存缓冲BufferedInputStream,BufferedOutputStream 缓冲区包装类 默认32个字节缓冲区的缓冲流内存/磁盘扇区一次读写操作所能完成最大字节数的整数倍(4的整数…

简单的SQL注入学习

引贴&#xff1a; http://blog.163.com/lucia_gagaga/blog/static/26476801920168184648754/ 首先需要编写一个php页面&#xff0c;讲php页面放入/opt/lampp/htdocs目录下&#xff1a; 解释一下这个页面&#xff1a; 1.通过if语句判断变量是否初始化 2.if语句中通过mysql_conne…

vb红绿灯自动切换_VB红绿灯程序

《VB红绿灯程序》由会员分享&#xff0c;可在线阅读&#xff0c;更多相关《VB红绿灯程序(4页珍藏版)》请在人人文库网上搜索。1、VB红绿灯演示Private Sub Command1_Click()While (1)Shape1.FillColor RGB(255, 0, 0)Shape2.FillColor RGB(0, 0, 0)Shape3.FillColor RGB(0, …

什么是网站监控?

网站监控是跟踪网站的可用性和性能&#xff0c;以最小化宕机时间&#xff0c;优化性能并确保顺畅的用户体验。维护网站正常运行对于任何企业来说都是至关重要的&#xff0c;因而对大多数业务来说&#xff0c;网站应用监控都是一个严峻的挑战。Applications Manager网站应用监控…

循序渐进PYTHON3(十三) --4-- DJANGO之CSRF使用

用 django 有多久&#xff0c;跟 csrf 这个概念打交道就有久。 每次初始化一个项目时都能看到 django.middleware.csrf.CsrfViewMiddleware 这个中间件每次在模板里写 form 时都知道要加一个 {% csrf_token %} tag每次发 ajax POST 请求&#xff0c;都需要加一个 X_CSRFTOKEN 的…

java string replace 重载_关于Java:如何使用replace(char,char)替换字符b的所有实例为空...

如何使用replace(char&#xff0c;char)将字符" b"的所有实例全部替换为空。例如&#xff1a;Hambbburger to Hamurger编辑&#xff1a;有一个约束&#xff0c;我只能使用1.4.2&#xff0c;这意味着没有重载版本的replace&#xff01;你不能因为什么都不是字符&#…

JavaScript——执行环境、变量对象、作用域链

前言 这几天在看《javascript高级程序设计》&#xff0c;看到执行环境和作用域链的时候&#xff0c;就有些模糊了。书中还是讲的不够具体。通过上网查资料&#xff0c;特来总结&#xff0c;以备回顾和修正。 目录&#xff1a; EC(执行环境或者执行上下文&#xff0c;Execution …

java线程interrupt用法_Java 如何中断线程

本篇文章帮大家学习java 如何中断线程&#xff0c;包含了Java 如何中断线程使用方法、操作技巧、实例演示和注意事项&#xff0c;有一定的学习价值&#xff0c;大家可以用来参考。以下实例演示了如何使用interrupt()方法来中断线程并使用 isInterrupted() 方法来判断线程是否已…

laravel5.4之artisan使用总结一

Artisan是laravel自带的命令行接口&#xff1a; php artisan list 编写命令 生成命令&#xff1a; 可以使用Artisan命令&#xff0c;php artisan make:command ConsoleTest 执行完这个命令后&#xff0c;会在app/Console/Commands 目录下创建ConsoleTest命令类。会包含默认的属…

java如何保证类不被回收_垃圾回收机制保证了Java程序不会出现内存溢出。( )

【简答题】1.激素(名词解释)【单选题】6.下列哪种情况下可引起ADH分泌增加【判断题】在Java中使用String类型的实例对象表示一个字符串。( )【判断题】static关键字可以修饰成员变量,也可以修饰局部变量。( )【单选题】建设项目投资控制应贯穿于建设工程全过程,在建设项目实施阶…

intellij idea 分屏设置 与快捷键

1、找到分屏功能 File -> setting -> keymap&#xff0c;搜索&#xff08;注意大小写&#xff09;&#xff1a;   Split Vertically 水平分屏   Split Horizontally 垂直分屏 2、设置快捷键&#xff0c; 编辑快捷键的地方在搜索框同一行&#xff1a;    在标签上直…

java parseexception_Java ParseException类代码示例

import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException; //导入依赖的package包/类Overridepublic void read(File file) throws IOException {try {Document doc db.parse(file);NodeList nlTimeSlots (NodeList) xp.evaluate("/ANNOTATION_DOCU…

bzoj 4016: [FJOI2014]最短路径树问题

Description 给一个包含n个点&#xff0c;m条边的无向连通图。从顶点1出发&#xff0c;往其余所有点分别走一次并返回。 往某一个点走时&#xff0c;选择总长度最短的路径走。若有多条长度最短的路径&#xff0c;则选择经过的顶点序列字典序最小的那条路径(如路径A为1,32,11&am…