龙空技术网

jsoncpp使用总结

物物互联梦动者 107

前言:

眼前你们对“jsoncpp使用”大约比较注意,小伙伴们都需要了解一些“jsoncpp使用”的相关资讯。那么小编同时在网摘上搜集了一些关于“jsoncpp使用””的相关文章,希望各位老铁们能喜欢,各位老铁们快快来了解一下吧!

一、jsoncpp介绍

jsoncpp是一个开源C++库,提供对JSON字符串序列化/反序列化的能力,开源地址:,文档地址:。

二、jsoncpp的使用

jsoncpp主要包含三种类型的C++类 - value、reader、writer。value表示json对象和数组。reader用于反序列化json字符串。writer用于序列化json字符串。简单使用示例:

示例1:生成json

Json::Value jsonRoot; //定义根节点Json::Value jsonItem; //定义一个子对象jsonItem["item1"] = "one"; //添加数据jsonItem["item2"] = 2;jsonRoot.append(jsonItem); jsonItem.clear(); //清除jsonItemjsonItem["item1.0"] = 1.0;jsonItem["item2.0"] = 2.0;jsonRoot["item"] = jsonItem;std::string strJson = jsonRoot.toStyledString(); //json结果

示例2:读取json

Json::Reader reader;string json_document = "{\"age\" : 123, \"name\" : \"weng\"}";	if (!reader.parse(json_document, json_object)){		cout << "error" << endl;		return 0;	}	else{		cout <<"age:" <<json_object["age"] << " name" << json_object["name"] << endl;	}

示例3:构造空数组

Json::Value root;  root["FurniturePlaceItemObject"].resize(0);  std::string strJson = root.toStyledString();

三、注意事项

1、jsoncpp不支持int64位的。

解决方法1:需要0.6.0rc2版本。 不要采用0.5.0版本,因为它没有64位int。

解决方法2:0.5.0版本基础上修改代码支持64位int。具体参考

解决方法3:asUInt换成asDouble

Json::Reader reader;Json::Value root;if (reader.parse(str, root)){//获取里面内容OutputDebugString(_T("STRING TO JSON \n"));//std::string str1 = root["messageType"].asString();long long tmstamp = ((long long)(root["sendTime"].asUInt()))/1000;WCHAR* wstr = NULL;TimestampToLocalTime(&wstr,tmstamp);}

结果发现第8行会出错,查了下错误原因, 原来SendTime是一个以毫秒为单位的时间戳,其值为1403575350411,这个值的大小远远超出了 unsigned int 或者 int的最大值,只能用INT64来表示, 但是看看Json::Value里面的函数只有asInt, asUint,没有取64位整数的函数,那怎么办呢?里面虽然没有64位的但是有一个asDouble,duoble的指数为11位,能表示的范围比Int64还大,所以上面的asUInt换成asDouble就可以了。

解决方法4:使用高版本(比如1.8.4),在使用jsoncpp库的工程属性预定义中增加JSON_HAS_INT64

2、对数据类型赋值比较严格。(比如将""引起来的字符串赋值给另一种类型,会报错 )

3、获取json中不存在名称的值,并且作为asCString()拷贝时,程序会core。如strncpy(a, root["test"].asCString(), sizeof(a));

4、fatal error C1083: 无法打开编译器生成的文件:“../../build/vs71/release/lib_json\json_value.asm”: No such file or directory

解决方法:修改生成静态库文件的工程的属性:路径为:菜单---项目--属性---配置属性---c/c++---输出文件---汇编程序输出:无列表

标签: #jsoncpp使用