您的位置:首页 > 编程语言 > C语言/C++

c++ Jsoncpp的安装及Json的解析和创建

2016-04-01 15:08 162 查看
参考 http://www.cnblogs.com/xudong-bupt/p/3696329.html
C++ Jsoncpp源代码编译与解析Json

1.Json 数据表示方式介绍

  

2.C++ Jsoncpp

2.1 Jsoncpp介绍

  (1)JsonCpp主要包含三种类型的class:Value Reader Writer;

    Json::Value 是jsoncpp 中最基本、最重要的类,用于表示各种类型的对象,jsoncpp 支持的对象类型可见 Json::ValueType 枚举值。

    Json::Reader 是用于读取的,说的确切点,是用于将字符串转换为 Json::Value 对象的。

    Json::Writer 类是一个纯虚类,并不能直接使用。在此我们使用 Json::Writer 的子类:Json::FastWriter、Json::StyledWriter、Json::StyledStreamWriter。

  (2)Jsoncpp中所有对象、类名都在namespace json中,包含json.h即可

2.2 Jsoncpp的下载与编译

  下载下来的jsoncpp必须要编译才能使用,在ubuntut上使用如下:

apt-get install scons

####http://sourceforge.net/projects/jsoncpp/
下载jsoncpp-src-0.5.0.tar.gz######

tar -xvzf jsoncpp-src-0.5.0.tar.gz

cd jsoncpp-src-0.5.0

scons platform=linux-gcc

  上面的命令执行完后,会在jsoncpp-src-0.5.0/libs/linux-gcc-4.6目录下面生成库文件:

  (1)libjson_linux-gcc-4.6_libmt.a

  (2)libjson_linux-gcc-4.6_libmt.so

  拷贝至其他路径时可以分别重命名为libjson.a和libjson.so. 至此,可以使用include 目录下的头文件和上述.so进行单独开发。

3.Jsoncpp使用代码示例

3.1 程序解析json数据

解析下面的文件JsonText,文件如下:

复制代码

{

"name": "json",

"array": [

"123",

"456",

"789"

]

}

1 #include "json/json.h"

2 #include <string>

3 #include <stdlib.h>

4 #include <iostream>

5 #include <fstream>

6 using namespace std;

7 int main()

8 {

9 ifstream is;

10 is.open ("JsonText", std::ios::binary );

11 Json::Reader reader;

12 Json::Value root;

13 if(reader.parse(is,root)) ///root保存整个Json对象的value

14 {

15 if(!root["name"].isNull())

16 {

17 cout<<root["name"].asString()<<endl; ///读取元素

18 Json::Value arrayObj = root["array"];

19 for(int i=0 ; i< arrayObj.size() ;i++)

20 {

21 cout<<arrayObj[i].asString()<<endl;

22 }

23 }

24 }

25 return 0;

26 }

编译、链接、执行:

  g++ c.cpp -I ./include/ -L./libs/linux-gcc-4.6/ -ljson_linux-gcc-4.6_libmt -o C

  ./C

执行结果:

  json

  123

  456

  789

3.2 程序生成json数据

1 #include <iostream>

2 #include <string>

3 #include "json/json.h"

4

5 int main(void)

6 {

7 Json::Value root;

8 Json::Value arrayObj;

9 Json::Value item;

10

11 for (int i = 0; i < 2; i ++)

12 {

13 item["key"] = i;

14 //arrayObj.append(item); ///给arrayObj中添加元素(arrayObj变为数组)

15 arrayObj.append(i); ///给arrayObj中添加元素(arrayObj变为数组)

16 }

17

18 root["key1"] = "value1"; ///给root中添加属性(arrayObj变为map)

19 root["key2"] = "value2";

20 root["array"] = arrayObj;

21 //root.toStyledString();

22 std::string out = root.toStyledString(); ///转换为json格式字符串

23 std::cout << out << std::endl;

24 return 0;

25 }

编译、链接、执行:

  g++ b.cpp -I ./include/ -L./libs/linux-gcc-4.6/ -ljson_linux-gcc-4.6_libmt -o B

  ./B

执行结果:

{

"array" : [ 0, 1 ],

"key1" : "value1",

"key2" : "value2"

}

以下参考 http://www.cppblog.com/wanghaiguang/archive/2013/12/26/205020.html

Json::Value 只能处理 ANSI 类型的字符串,如果 C++ 程序是用 Unicode 编码的,最好加一个 Adapt 类来适配。

下面是从网上找的代码示例:

1. 从字符串解析json

const char* str = "{\"uploadid\": \"UP000000\",\"code\": 100,\"msg\": \"\",\"files\": \"\"}";

Json::Reader reader;

Json::Value root;

if (reader.parse(str, root)) // reader将Json字符串解析到root,root将包含Json里所有子元素

{

std::string upload_id = root["uploadid"].asString(); // 访问节点,upload_id = "UP000000"

int code = root["code"].asInt(); // 访问节点,code = 100

}
2. 从文件解析json

int ReadJsonFromFile(const char* filename)

{

Json::Reader reader;// 解析json用Json::Reader

Json::Value root; // Json::Value是一种很重要的类型,可以代表任意类型。如int, string, object, array


std::ifstream is;

is.open (filename, std::ios::binary );

if (reader.parse(is, root, FALSE))

{

std::string code;

if (!root["files"].isNull()) // 访问节点,Access an object value by name, create a null member if it does not exist.

code = root["uploadid"].asString();

code = root.get("uploadid", "null").asString();// 访问节点,Return the member named key if it exist, defaultValue otherwise.

int file_size = root["files"].size(); // 得到"files"的数组个数

for(int i = 0; i < file_size; ++i) // 遍历数组

{

Json::Value val_image = root["files"][i]["images"];

int image_size = val_image.size();

for(int j = 0; j < image_size; ++j)

{

std::string type = val_image[j]["type"].asString();

std::string url = val_image[j]["url"].asString();

printf("type : %s, url : %s \n", type.c_str(), url.c_str());

}

}

}

is.close();

return 0;

}
3. 向文件中插入json

void WriteJsonData(const char* filename)

{

Json::Reader reader;

Json::Value root; // Json::Value是一种很重要的类型,可以代表任意类型。如int, string, object, array


std::ifstream is;

is.open (filename, std::ios::binary );

if (reader.parse(is, root))

{

Json::Value arrayObj; // 构建对象

Json::Value new_item, new_item1;

new_item["date"] = "2011-11-11";

new_item1["time"] = "11:11:11";

arrayObj.append(new_item); // 插入数组成员

arrayObj.append(new_item1); // 插入数组成员

int file_size = root["files"].size();

for(int i = 0; i < file_size; ++i)

root["files"][i]["exifs"] = arrayObj; // 插入原json中

std::string out = root.toStyledString();

// 输出无格式json字符串

Json::FastWriter writer;

std::string strWrite = writer.write(root);

std::ofstream ofs;

ofs.open("test_write.json");

ofs << strWrite;

ofs.close();

}

is.close();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: