jsoncpp的api简要说明

1  jsoncpp的api简要说明

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

std::string strDataJson;

Json::Reader JReader; 

Json::Value JObject;

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

{

cerr << "parse json error." << endl;

return bSuccess;

}

 

2,读取

std::string strMsg = JRec["msg"].asString();

int nRetCode = JRec["ret"]..asInt();

Json::Value JList = JRec["data"]["list"];

int nSize = JList.size();

 

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

 

3,增加或修改

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

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

 

4,删除

JValue.removeMember("toberemove");

 

5,对象转为字符串

//输出无格式json字符串

Json::FastWriter fast_writer;

strJRecList = fast_writer.write(JRoot);

 

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

std::string strOut = JRoot.toStyledString();

#include "json/json.h"
const string fileName = "json.txt";

int main(int argc, char *argv[])
{
    string line;
    std::ifstream in(fileName.c_str());
    if(!in)
        return 0;

    std::getline(in, line);

    Json::Reader reader;  
    Json::Value root;  

    if(reader.parse(line, root))
        cout << "suc" << endl;
    else
        cout << "fail" << endl;

   cout << root["status"].asInt() << endl;
   cout << root["msg"].asString() << endl;
   cout << root["forbidReason"].asString() << endl;

 

    Json::Value root, ipPort;
    string host;
    unsigned int port = 0;

    if(addrs.size() == 0)
        root["hosts"].append(ipPort);
    else
    {   
        for(size_t i = 0; i < addrs.size(); i++)
        {   
            if(getIpAndPort(addrs[i], host, port))
            {   
                ipPort["ip"] = host;
                ipPort["port"] = port;
            }   
            root["hosts"].append(ipPort);
        }   
    }

 

http://blog.csdn.net/u014489596/article/details/44920557

 

son是一种数据交换格式,比较适合编写和阅读。jsoncpp是采用c++语言编写的用来处理json格式的第三包。直接来说明改如何使用它,本文是基于windows下的。

 

在github上下载jsoncpp的源代码包:https://github.com/open-source-parsers/jsoncpp。解压后用vs打开/makefiles/vs71/jsoncpp.sln项目,选择lib_json项目编译来生成lib文件,为了方便,debug和release都需要生成。

 

创建一个win32的空项目,将生成的lib文件包含,附加包含目录添加源代码中的include文件夹。后面简单说下比较常用的几种json处理方法。

 

解析json对象:

 

1.首先看看最简单的一种json格式,只有键-值的一重嵌套:

{

“id” : 123,

"name" : "wu"

}

我们直接将上面的数据初始化到到string对象中,方便解析,后面都是如此

 

[cpp] view plaincopy
 
  1. std::string json = "{\"id\" : 123, \"name\" : \"wu\"}";  
  2.   
  3. Json::Reader reader;    
  4. Json::Value root;    
  5. std::string name;  
  6. int id = 0;  
  7. if (reader.parse(json, root))  // reader将Json字符串解析到root,root将包含Json里所有子元素     
  8. {    
  9.     name = root["name"].asString();  
  10.     id = root["id"].asInt();  
  11. }  


        2.再看看数组的:

 

[ { "id" : 1, "name" : "wu"},  {"id":2, "name" : "tan"} ]

 

[cpp] view plaincopy
 
  1. std::string json = "[ {\"id\" : 1, \"name\" : \"wu\"}, {\"id\" : 2, \"name\" : \"tan\"} ]";  
  2.   
  3. Json::Reader reader;    
  4. Json::Value root;    
  5. std::string name;  
  6. int id = 0;  
  7. std::map<int, std::string> mapJson;  
  8.   
  9. if (reader.parse(json, root))  // reader将Json字符串解析到root,root将包含Json里所有子元素     
  10. {    
  11.     for (int i = 0; i < root.size(); ++i)  
  12.     {  
  13.         name = root[i]["name"].asString();  
  14.         id = root[i]["id"].asInt();  
  15.   
  16.         mapJson[id] = name;  
  17.     }  
  18. }   


        3.如果是这样的数组:

 

{

“id” : [1, 2],

"name" : ["wu", "tan"]

}

[cpp] view plaincopy
 
  1. std::string json = "{\"id\" : [1, 2], \"name\" : [\"wu\", \"tan\"] } ";  
  2.   
  3. Json::Reader reader;    
  4. Json::Value root;    
  5. std::string name;  
  6. int id = 0;  
  7.   
  8. if (reader.parse(json, root))  // reader将Json字符串解析到root,root将包含Json里所有子元素     
  9. {    
  10.     for (int i = 0; i < root["id"].size(); ++i)  
  11.     {  
  12.         id = root["id"][i].asInt();  
  13.     }  
  14.   
  15.     for (int i = 0; i < root["name"].size(); ++i)  
  16.     {  
  17.         name = root["name"][i].asString();  
  18.     }  
  19. }   

 

这种情况其实和上一种是类似的。

 

4.看看多重嵌套的情况,为了简便,我们嵌套两层:

{

"id" : 1,

"data" : {

"name" : "wu",

“age” : 26

}

}

[cpp] view plaincopy
 
  1. std::string json = "{\"id\" : 1, \"data\" : { \"name\" : \"wu\",  \"age\" : 26 } }";  
  2.   
  3. Json::Reader reader;    
  4. Json::Value root;    
  5. std::string name;  
  6. int id = 0;  
  7. int age = 0;  
  8.   
  9. if (reader.parse(json, root))  // reader将Json字符串解析到root,root将包含Json里所有子元素     
  10. {    
  11.     id = root["id"].asInt();  
  12.     name = root["data"]["name"].asString();  
  13.     age = root["data"]["age"].asInt();  
  14. }   

 

其实这种情况和第一种的类似,只是通过root["key"]取到的还是键值对,继续通过key取值即可。

基本上再复杂的数据格式也是上面几种情况的组合而已。

 

json对象的生成:

1.生成上面第一种情况的json格式:

 

[cpp] view plaincopy
 
  1. Json::Value root;    
  2.   
  3. root["id"] = 123;  
  4. root["name"] = "wu";  
  5.       
  6. std::string json = root.toStyledString();  


我们会将生成的json对象序列化到string对象中去,后面也是如此。

 

 

2.生成上面第二种情况的json:

 

[cpp] view plaincopy
 
  1. Json::Value root;  
  2.   
  3. for (int i = 0; i < 2; ++i)  
  4. {  
  5.     root[i]["id"] = i + 1;  
  6.   
  7.     if (0 == i)  
  8.     {  
  9.         root[i]["name"] = "wu";  
  10.     }  
  11.     else  
  12.     {  
  13.         root[i]["name"] = "tan";  
  14.     }  
  15. }  
  16.   
  17. std::string json = root.toStyledString();  


还可以这样生成:

 

 

[cpp] view plaincopy
 
  1. Json::Value root;  
  2. Json::Value item;  
  3.   
  4. for (int i = 0; i < 2; ++i)  
  5. {  
  6.     item["id"] = i + 1;  
  7.   
  8.     if (0 == i)  
  9.     {  
  10.         item["name"] = "wu";  
  11.     }  
  12.     else  
  13.     {  
  14.         item["name"] = "tan";  
  15.     }  
  16.           
  17.     root.append(item);  
  18. }  
  19.   
  20. std::string json = root.toStyledString();  


3.生成上面第三种情况的json:

 

 

[cpp] view plaincopy
 
  1. Json::Value root;  
  2.   
  3. for (int i = 0; i < 2; ++i)  
  4. {  
  5.     root["id"].append(i);  
  6.   
  7.     if (0 == i)  
  8.     {  
  9.         root["name"].append("wu");  
  10.     }  
  11.     else  
  12.     {  
  13.         root["name"].append("tan");  
  14.     }  
  15.   
  16. }  
  17.   
  18. std::string json = root.toStyledString();  


4.生成上面第四种情况的json:

 

 

[cpp] view plaincopy
 
  1. Json::Value root;  
  2.   
  3. root["id"] = 1;  
  4. root["data"]["name"] = "wu";  
  5. root["data"]["age"] = 26;  
  6.   
  7. std::string json = root.toStyledString();  



其实解析和生成json是互逆的,只要明白这几种情况,其他的无非是这几种情况的各种组合,原理是一样的。

 

版权声明:本文为博主原创文章,未经博主允许不得转载。

 

posted @ 2015-08-26 11:49  穆穆兔兔  阅读(3723)  评论(0编辑  收藏  举报