一、从字符串中读取JSON

a.cpp

?
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
#include <iostream>
 
#include "json/json.h"
 
using namespace std;
 
int main()
{
    //字符串
    const char* str = 
        "{\"praenomen\":\"Gaius\",\"nomen\":\"Julius\",\"cognomen\":\"Caezar\","
        "\"born\":-100,\"died\":-44}";
 
    Json::Reader reader;
    Json::Value root;
 
    //从字符串中读取数据
    if(reader.parse(str,root))
    {
        string praenomen = root["praenomen"].asString();
        string nomen = root["nomen"].asString();
        string cognomen = root["cognomen"].asString();
        int born = root["born"].asInt();
        int died = root["died"].asInt();
 
        cout << praenomen + " " + nomen + " " + cognomen
            << " was born in year " << born 
            << ", died in year " << died << endl;
    }
 
    return 0;
}

makefile文件

?
1
2
3
4
5
6
7
8
LIB=-L/usr/local/lib/libjson/ -ljson_linux-gcc-4.4.7_libmt
 
a: a.o
    g++ -o a -std=c++0x a.o $(LIB)
a.o: a.cpp 
    g++ -c a.cpp
clean:
    rm -rf a.o a

执行结果

二、从文件里读取JSON

PersonalInfo.json(一个存储了JSON格式字符串的文件)

?
1
2
3
4
5
6
7
8
9
10
11
12
{
    "name":"Tsybius",
    "age":23,
    "sex_is_male":true,
    "partner":
    {
        "partner_name":"Galatea",
        "partner_age":21,
        "partner_sex_is_male":false
    },
    "achievement":["ach1","ach2","ach3"]
}

a.cpp

?
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
#include <iostream>
#include <fstream>
 
#include "json/json.h"
 
using namespace std;
 
int main()
{
    Json::Reader reader;
    Json::Value root;
 
    //从文件里读取
    ifstream is;
    is.open("PersonalInfo.json", ios::binary);
 
    if(reader.parse(is,root))
    {
        //读取根节点信息
        string name = root["name"].asString();
        int age = root["age"].asInt();
        bool sex_is_male = root["sex_is_male"].asBool();
 
        cout << "My name is " << name << endl;
        cout << "I'm " << age << " years old" << endl;
        cout << "I'm a " << (sex_is_male ?

"man" "woman") << endl;

 
        //读取子节点信息
        string partner_name = root["partner"]["partner_name"].asString();
        int partner_age = root["partner"]["partner_age"].asInt();
        bool partner_sex_is_male = root["partner"]["partner_sex_is_male"].asBool();
 
        cout << "My partner's name is " << partner_name << endl;
        cout << (partner_sex_is_male ? "he" "she") << " is "
            << partner_age << " years old" << endl;
 
        //读取数组信息
        cout << "Here's my achievements:" << endl;
        for(int i = 0; i < root["achievement"].size(); i++)
        {
            string ach = root["achievement"][i].asString();
            cout << ach << '\t';
        }
        cout << endl;
 
        cout << "Reading Complete!" << endl;
    }
 
    is.close();
 
    return 0;
}

makefile

?
1
2
3
4
5
6
7
8
LIB=-L/usr/local/lib/libjson/ -ljson_linux-gcc-4.4.7_libmt
 
a: a.o
    g++ -o a -std=c++0x a.o $(LIB)
a.o: a.cpp 
    g++ -c a.cpp
clean:
    rm -rf a.o a

执行结果

三、将信息保存为JSON格式

a.cpp

?
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
#include <iostream>
#include <fstream>
 
#include "json/json.h"
 
using namespace std;
 
int main()
{
    //根节点
    Json::Value root;
 
    //根节点属性
    root["name"] = Json::Value("Tsybius");
    root["age"] = Json::Value(23);
    root["sex_is_male"] = Json::Value(true);
 
    //子节点
    Json::Value partner;
 
    //子节点属性
    partner["partner_name"] = Json::Value("Galatea");
    partner["partner_age"] = Json::Value(21);
    partner["partner_sex_is_male"] = Json::Value(false);
 
    //子节点挂到根节点上
    root["partner"] = Json::Value(partner);
 
    //数组形式
    root["achievement"].append("ach1");
    root["achievement"].append("ach2");
    root["achievement"].append("ach3");
     
    //直接输出
    cout << "FastWriter:" << endl;
    Json::FastWriter fw;
    cout << fw.write(root) << endl << endl;
 
    //缩进输出
    cout << "StyledWriter:" << endl;
    Json::StyledWriter sw;
    cout << sw.write(root) << endl << endl;
     
    //输出到文件
    ofstream os;
    os.open("PersonalInfo");
    os << sw.write(root);
    os.close();
 
    return 0;
}

makefile

?
1
2
3
4
5
6
7
8
LIB=-L/usr/local/lib/libjson/ -ljson_linux-gcc-4.4.7_libmt
 
a: a.o
    g++ -o a -std=c++0x a.o $(LIB)
a.o: a.cpp 
    g++ -c a.cpp
clean:
    rm -rf a.o a

执行结果

生成的文件PersonalInfo.json

?
1
2
3
4
5
6
7
8
9
10
11
{
   "achievement" : [ "ach1""ach2""ach3" ],
   "age" : 23,
   "name" "Tsybius",
   "partner" : {
      "partner_age" : 21,
      "partner_name" "Galatea",
      "partner_sex_is_male" false
   },
   "sex_is_male" true
}

END

C++操作Json字符串的更多相关文章

  1. JS 操作JSON字符串

    用Js的eval解析JSON中的注意点 在JS中将JSON的字符串解析成JSON数据格式,一般有两种方式: 1.一种为使用eval()函数. 2. 使用Function对象来进行返回解析. 使用eva ...

  2. 使用 Newtonsoft.Json 操作 JSON 字符串

    一.把实体类转化为 JSON 字符串 1. 为实体类赋值 SenderFromMQSearch senderFromMQSearch = new SenderFromMQSearch(); sende ...

  3. Newtonsoft.Json 操作 JSON 字符串

    Newtonsoft.Json介绍 在做开发的时候,很多数据交换都是以json格式传输的.而使用Json的时候,我们很多时候会涉及到几个序列化对象的使用:DataContractJsonSeriali ...

  4. 基于 Vue.js 之 iView UI 框架非工程化实践记要 使用 Newtonsoft.Json 操作 JSON 字符串 基于.net core实现项目自动编译、并生成nuget包 webpack + vue 在dev和production模式下的小小区别 这样入门asp.net core 之 静态文件 这样入门asp.net core,如何

    基于 Vue.js 之 iView UI 框架非工程化实践记要   像我们平日里做惯了 Java 或者 .NET 这种后端程序员,对于前端的认识还常常停留在 jQuery 时代,包括其插件在需要时就引 ...

  5. java操作JSON字符串转换成对象的时候如何可以不建立实体类也能获取数据

    引入依赖 <dependency>    <groupId>com.alibaba</groupId>    <artifactId>fastjson& ...

  6. 让C#可以像Javascript一样操作Json

    Json的简介 JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.它基于ECMAScript的一个子集. JSON采用完全独立于语言的文本格式,但是也使用了 ...

  7. C# 技巧(3) C# 操作 JSON

    RestAPI中, 经常需要操作json字符串,  需要把json字符串"反序列化"成一个对象, 也需要把一个对象"序列化"成一字符串. C# 操作json, ...

  8. .NET操作JSON

    http://www.cnblogs.com/txw1958/archive/2012/08/01/csharp-json.html JSON文件读入到内存中就是字符串,.NET操作JSON就是生成与 ...

  9. C#操作JSON学习

    JSON(全称为JavaScript Object Notation) 是一种轻量级的数据交换格式.它是基于JavaScript语法标准的一个子集. JSON采用完全独立于语言的文本格式,可以很容易在 ...

随机推荐

  1. vim下阅读代码时标签跳转设置

    1.在fedora14中的 /etc/vimrc下,加入如下几行,可根据源代码工程文件的结构来定 2. 在源代码工程内,输入如下命令 ctags -R 当前目录下将生成一个tags文件 3.查看源代码 ...

  2. mysql_数据查询_连接查询

    连接查询 1.连接(join) 也称θ连接,从两个关系的笛卡尔积中选择属性间满足一定条件的元组. 等值连接:θ为“=”的连接运算称为等值连接.从关系R和S的广义笛卡尔积中选取A.B属性值相等的元组. ...

  3. day07-列表类型/元组类型/字典类型/集合类型内置方法

    目录 列表类型内置方法 元组类型内置方法 字典类型内置方法 集合类型内置方法 列表类型内置方法 用来存多个元素,[]内用逗号隔开任意数据类型的元素 1. list()强制类型转换 print(list ...

  4. MFC CAD控制权问题

    begineditorcommand(); 隐藏对话框  把控制权交给CAD completeeditorcommand(); 完成交互返回到应用程序 canceleditorcommand CAD被 ...

  5. lsof command not found 解决

    有些centos 没有 lsof命令,需要安装 yum install lsof -y 使用: lsof -i:端口号

  6. react typescript 父组件调用子组件

    //父组件import * as React from 'react'import { Input } from 'antd'const Search = Input.Searchimport &qu ...

  7. swift--如何设置子视图alpha不同于父视图

    //1.2加入商家标题评分容器 let titleWarp=UIView(frame: CGRectMake(, , screenObject.width, )); titleWarp.backgro ...

  8. auto类型推导

    引言 auto : 类型推导. 在使用c++的时候会经常使用, 就像在考虑STL时迭代器类型, 写模板的时候使用auto能少写代码, 也能帮助我们避免一些隐患的细节. auto初始化 使用auto型别 ...

  9. 使用python的几个小经验(查看文档)

    好久没有水博客了,未来再过20天不到的时间又得参加软考,今天终于得好好水一发帖子 关于Python,很多人包括我之前都不知道怎么找文档,现在有一个好办法,就是在命令行模式下调用pydoc –p xxx ...

  10. Linux之iptables(二、基本认识和组成)

    iptables的基本认识 Netfilter组件 内核空间,集成在linux内核中 扩展各种网络服务的结构化底层框架 内核中选取五个位置放了五个hook(勾子) function(INPUT.OUT ...