微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

jsoncpp第二篇------API

更多API参考jsoncpp头文件

1 jsoncpp的api简要说明

1,解析(json字符串转为对象)

std::stringstrDataJson;

Json::ReaderJReader;

Json::ValueJObject;

if(!JReader.parse(strDataJson,JObject))

{

cerr<<"parsejsonerror."<<endl;

returnbSuccess;

}


2,读取

std::stringstrMsg=JRec["msg"].asstring();

intnRetCode=JRec["ret"]..asInt();

Json::ValueJList=JRec["data"]["list"];

intnSize=JList.size();

获取错误信息:JReader.getFormatedErrorMessages()

3,增加修改

JRoot["stringdata"]=Json::Value("msg");

JRoot["intdata"]=Json::Value(10);

4,删除

JValue.removeMember("toberemove");

5,对象转为字符串

//输出无格式json字符串

Json::FastWriterfast_writer;

strJRecList=fast_writer.write(JRoot);

//格式化之后的json,有回车换行符

std::stringstrOut=JRoot.toStyledString();

转自;http://my.oschina.net/chenleijava/blog/144312


6各种json子类型的使用

(1)json Object

 for (Json::ValueIterator iter=groups_config.begin(); iter!=groups_config.end();iter++) {
      Json::Value client_dict = (*iter)["clients"];
      string topic_recresult = (*iter)["topics"]["recresult"].asstring();
      string topic_recreq = (*iter)["topics"]["recreq"].asstring();
      string topic_input = (*iter)["topics"]["input"].asstring();
      for (Json::ValueIterator client_iter=client_dict.begin(); client_iter != client_dict.end(); ++client_iter) {
        string cid = client_iter.key().asstring();
        // FIXME: create a new customer configuration
        CustomerPtr c(new Customer);
        c->LoadFromJson(cid,(*client_iter),topic_recresult,topic_recreq,topic_input);
        customers[cid] = c;
      }
    }



2 详细API

</pre><pre code_snippet_id="342950" snippet_file_name="blog_20140513_1_8471295" name="code" class="cpp">class JSONAPI_API JsonValue
	{
		typedef std::map<std::string,JsonValue*>	InnerMap;
		typedef std::vector<JsonValue*>				InnerVector;

	public:
		JsonValue();
		virtual ~JsonValue();

	public:
		void clear();

		//import/export
		void parse(const char* jsonString);
		JsonString toString();
		JsonString toString_styled();
		void toFile(const char* filename);
		void toFile_styled(const char* filename);

		//set
		void operator=(JsonValue& jval);

		void operator=(char vInteger);
		void operator=(unsigned char vInteger);
		void operator=(short vInteger);
		void operator=(unsigned short vInteger);
		void operator=(long vInteger);
		void operator=(unsigned long vInteger);
		void operator=(int vInteger);
		void operator=(unsigned int vInteger);
		void operator=(__int64 vInteger);
		void operator=(unsigned __int64 vInteger);
		void operator=(float vReal);
		void operator=(double vReal);
		void operator=(bool vBoolean);
		void operator=(const char* vString);

		int append(JsonValue& jval);
		int append(char vInteger);
		int append(unsigned char vInteger);
		int append(short vInteger);
		int append(unsigned short vInteger);
		int append(long vInteger);
		int append(unsigned long vInteger);
		int append(int vInteger);
		int append(unsigned int vInteger);
		int append(__int64 vInteger);
		int append(unsigned __int64 vInteger);
		int append(float vReal);
		int append(double vReal);
		int append(bool vBoolean);
		int append(const char* vString);

		//get
		JsonValue& operator [](const char* name);
		JsonValue& operator [](unsigned int arrIdx0);

		//get final value
		char			getChar();
		unsigned char	getUChar();
		short			getShort();
		unsigned short	getUShort();
		long			getLong();
		unsigned long	getULong();
		int				getInt();
		unsigned int	getUInt();
		__int64			getInt64();
		unsigned __int64 getUInt64();
		bool			getBoolean();
		float			getFloat();
		double			getDouble();
		const char*		getString();

		//check
		bool isNull();
		bool isChar();
		bool isUChar();
		bool isShort();
		bool isUShort();
		bool isLong();
		bool isULong();
		bool isInt();
		bool isUInt();
		bool isInt64();
		bool isUInt64();
		bool isBoolean();
		bool isFloat();
		bool isDouble();
		bool isstring();
		bool isObject();
		bool isArray();

	protected:
		ValueType m_valueType;
		union
		{
			__int64 m_integer;
			double m_real;
			bool m_boolean;
			char* m_string;
			InnerMaP* m_kv;
			InnerVector* m_array;
		}m_v;

	protected:
		void setAsObject();
		void setAsArray();

		friend JValHelper;
	};



1.jsoncpp是什么?

jsoncpp是一个使用C++语言来解析json文件的开源库,其项目地址为:http://sourceforge.net/projects/jsoncpp/,属于免费项目,任何人都可以下载使用

2. 编译jsoncpp

jsoncpp文件中提供了vs71的工程文件以及makerelease.py文件,用来编译,里面分为jsontest、lib_json、test_lib_json三个工程,按照自己需要的编译。

注意:如果使用VS认的编译选项MTd或者MT,在使用json_libmtd.lib的时候可能会出现LNK2038错误(我使用的VS2012 vc110环境)所以请修改MTD为MDd,MT为MD

3.使用jsoncpp读JSON文件

如何将lib库添加进VS工程中在此就不赘述了。先看第一个文件的例

// JSON文件
{"address":[
    {"name":"eliteYang","email":"elite_yang@163.com"},{"name":"AAA","email":"aaa@163.com"},{"name":"BBB","email":"bbb@163.com"}
]}

/**
 * file     :   jsoncpp_test.cpp
 * author   :   eliteYang
 * email    :   elite_yang@163.com
 * blog     :   http://www.cppfasn.org
 * desc     :   json cpp test
 */
 
#include <fstream>
#include <string>
#include "jsoncpp/json.h"
 
int _tmain(int argc,_TCHAR* argv[])
{
    std::ifstream ifs;
    ifs.open("test.json");
 
    Json::Reader reader;
    Json::Value root;
    if (!reader.parse(ifs,root,false))
    { return -1; }
 
    Json::Value add_value = root["address"];
    for (int i = 0; i < add_value.size(); ++i)
    {
        Json::Value temp_value = add_value[i];
        std::string strName = temp_value["name"].asstring();
        std::string strMail = temp_value["email"].asstring();
        std::cout << "name: " << strName << " email: " << strMail << std::endl;
 
        // use value array[index]
        //Json::Value temp_value = add_value[i];
        //std::string strName = add_value[i]["name"].asstring();
        //std::string strMail = add_value[i]["email"].asstring();
        //std::cout << "name: " << strName << " email: " << strMail << std::endl;
    }
 
    system("Pause");
 
    return 0;
}

结果:

name: eliteYang email: elite_yang@163.com
name: AAA email: aaa@163.com
name: BBB email: bbb@163.com
请按任意键继续. . .

跟我们文件中的数据完全一致。

4.使用JSON写入一块数据

我们继续使用上述文件,在中间加上一块数据。我们插入一个新的{"name": "append","email": "append@163.com"}

/**
 * file     :   jsoncpp_test.cpp
 * author   :   eliteYang
 * email    :   elite_yang@163.com
 * blog     :   http://www.cppfasn.org
 * desc     :   json cpp test
 */
 
#include <fstream>
#include <string>
#include "jsoncpp/json.h"
 
int _tmain(int argc,false))
    { return -1; }
 
    Json::Value& add_value = root["address"];
    Json::Value append_value;
    append_value["name"] = "append";
    append_value["email"] = "append@163.com";
    add_value.append(append_value);
 
    for (int i = 0; i < add_value.size(); ++i)
    {
        Json::Value temp_value = add_value[i];
        std::string strName = temp_value["name"].asstring();
        std::string strMail = temp_value["email"].asstring();
        std::cout << "name: " << strName << " email: " << strMail << std::endl;
    }
 
    Json::FastWriter writer;
    std::string json_append_file = writer.write(root);
 
    std::ofstream ofs;
    ofs.open("test_append.json");
    ofs << json_append_file;
 
    system("Pause");
 
    return 0;
}

结果:

name: eliteYang email: elite_yang@163.com
name: AAA email: aaa@163.com
name: BBB email: bbb@163.com
name: append email: append@163.com
请按任意键继续. . .
// test_append.json
{"address":[{"email":"elite_yang@163.com","name":"eliteYang"},{"email":"aaa@163.com","name":"AAA"},{"email":"bbb@163.com","name":"BBB"},{"email":"append@163.com","name":"append"}]}

转自:http://www.cppfans.org/1445.html



一个jsoncpp的例子

使用jsoncpp进行字符串、数字、布尔值和数组的封装与解析。

1)下载jsoncpp的代码百度网盘地址 :http://pan.baidu.com/s/1ntqQhIT

2)解压缩文件 jsoncpp.rar

unzip jsoncpp.rar

3)修改jsoncpp/src/main.cpp文件

vim src/main.cpp
  1 #include <string>
  2 #include <json/json.h>
  3 #include "stdio.h"
  4 
  5 int ReadJson(const std::string &);
  6 std::string writeJson();
  7 
  8 int main(int argc,char** argv)
  9 {
 10     using namespace std;
 11 
 12     std::string strMsg;
 13 
 14     cout<<--------------------------------"<<endl;
 15     strMsg = writeJson();
 16     cout<< json write : " << endl << strMsg << endl;
 17     cout<< 18     cout<< json read :" << endl;
 19     ReadJson(strMsg);
 20     cout<< 21 
 22     return 0;
 23 }
 24 
 25 string & strValue) 
 26 {
 27      28 
 29     Json::Reader reader;
 30     Json::Value value;
 31 
 32     if (reader.parse(strValue,value))
 33     {
 34         //解析json中的对象
 35         string out = value[name"].asstring();
 36         cout << name : "   << out << endl;
 37         cout << number : " << value[number"].asInt() << endl;
 38         cout << value : "  << value[value"].asBool() << endl;
 39         cout << no such num : haha 40         cout << no such str : hehe"].asstring() << endl;
 41 
 42         解析数组对象
 43         const Json::Value arrayNum = value[arrnum"];
 44         for (unsigned int i = 0; i < arrayNum.size(); i++)
 45         {
 46             cout << arrnum[" << i << ] = " << arrayNum[i];
 47         }
 48         解析对象数组对象
 49         Json::Value arrayObj = value[array 50         cout << array size = " << arrayObj.size() << endl;
 51         for(unsigned 0; i < arrayObj.size(); i++)
 52         {
 53             cout << arrayObj[i];
 54         }
 55         从对象数组中找到想要的对象
 56          57         {
 58             if (arrayObj[i].isMember(string")) 
 59             {
 60                 out = arrayObj[i][ 61                 std::cout << string : " << out << std::endl;
 62             }
 63         }
 64     }
 65 
 66      67 }
 68 
 69 std::string writeJson() 
 70 {
 71      72 
 73     Json::Value root;
 74     Json::Value arrayObj;
 75     Json::Value item;
 76     Json::Value iNum;
 77 
 78     item["]    = this is a string";
 79     item[999;
 80     item[aaaaaabbbbbb 81     arrayObj.append(item);
 82 
 83     直接对jsoncpp对象以数字索引作为下标进行赋值,则自动作为数组
 84     iNum[1] = 1;
 85     iNum[2] = 2;
 86     iNum[3] = 3;
 87     iNum[4] = 4;
 88     iNum[5] = 5;
 89     iNum[6] = 6;
 90 
 91     增加对象数组
 92     root["]    = arrayObj;
 93     增加字符串
 94     root[json 95     增加数字
 96     root[666;
 97     增加布尔变量
 98     root["]    = true;
 99     增加数字数组
100     root["]    = iNum;
101 
102     root.toStyledString();
103     out = root.toStyledString();
104 
105     return out;
106 }

4)在目录jsoncpp/ 下执行make命令

jsoncpp$ make
mkdir -p objs/src/json;  mkdir -p objs/src;
g++ -c -Wall -Werror -g -I include src/json/json_reader.cpp -o objs/src/json/json_reader.o
g++ -c -Wall -Werror -g -I include src/json/json_value.cpp -o objs/src/json/json_value.o
g++ -c -Wall -Werror -g -I include src/json/json_writer.cpp -o objs/src/json/json_writer.o
g++ -c -Wall -Werror -g -I include src/main.cpp -o objs/src/main.o
g++  objs/src/json/json_reader.o objs/src/json/json_value.o objs/src/json/json_writer.o objs/src/main.o -o main
5)运行jsoncpp/下的main文件

./main

6)运行结果如下

fengbo: jsoncpp$ ./main 
--------------------------------
json write : 
{
   " : [
      {
         " : ",999,0); line-height:1.5!important">"
      }
   ],0); line-height:1.5!important">" : [ null,1,128); line-height:1.5!important">2,128); line-height:1.5!important">3,128); line-height:1.5!important">4,128); line-height:1.5!important">5,128); line-height:1.5!important">6 ],128); line-height:1.5!important">666,0); line-height:1.5!important">" : true
}

--------------------------------
json read :
name : json
number : 666
value : 1
no such num : 0
no such str : 
arrnum[0] = null
arrnum[1
arrnum[2
arrnum[3
arrnum[4
arrnum[5
arrnum[6
array size = 1

{
    "
}
string : this is a string
--------------------------------

作者:风波

mail : fengbohello@qq.com



jsoncpp使用优化:http://www.searchtb.com/2012/11/jsoncpp-optimization.html

JsonCpp使用优化

http://www.searchtb.com/2012/11/jsoncpp-optimization.htmlJsonCpp使用优化

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


AJAX是一种基于JavaScript和XML的技术,能够使网页实现异步交互,节省带宽和时间,提高用户体验。在使用AJAX时,需要通过解析JSON格式的数据,来获取所需要的数据。
在网页开发中,我们常常需要通过Ajax从后端获取数据并在页面中展示出来。其中,JSON是一种常用的数据格式。那么,在使用Ajax获取JSON数据后,如何将数据取出来呢?
在前端开发中,经常需要循环JSON对象数组进行数据操作。使用AJAX技术可以在不刷新页面的情况下异步获取数据。那么我们该如何循环JSON对象数组呢?下面我们通过一段代码来进行讲解。
AJAX(Asynchronous JavaScript and XML)是一种用于创建 Web 应用程序的技术,它使用 JavaScript 和 XML(或 JSON)来在后台异步传输数据。
AJAX技术被广泛应用于现代Web开发,它可以在无需重新加载页面的情况下,向服务器发出请求并更新页面,实现了异步更新的效果。而传递JSON数据是AJAX中比较常见的一种方法,下面是如何使用AJAX传递JSON数据的详细介绍。
Ajax是一种通过JavaScript和HTTP请求交互的技术,可以实现无需刷新页面的异步数据交互。在处理数据时,常常需要删除一些已存在的数据。本文将介绍如何使用Ajax删除JSON数据库中的数据。
在使用Ajax时,我们经常需要将数据格式化为JSON格式。JSON是一种轻量级数据交换格式,它以键值对的形式来表达数据。
AJAX是一种支持异步请求的技术,它可以让前端页面不用刷新就能向后台请求数据,并异步地展示给用户,提高了用户的体验感。其中,使用JSON格式化数据可以帮助我们更方便快捷地处理返回的数据。
AJAX是一种前端技术,可以通过异步请求来获取数据,并在页面上更新它们。JSON是一种轻量级的数据交换格式,因为它易于读取和编写,因此在Web应用程序中被广泛使用。AJAX传送JSON数据是一种常见的技术,可以让Web应用
在前端开发中,ajax是很常见的技术,它可以在不刷新整个页面的情况下请求服务器数据和更新部分页面。而当需要遍历多个json文件时,可以使用ajax循环遍历来实现。