jsoncpp的api简要说明

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

  1. for(Json::ValueIteratoriter=groups_config.begin();iter!=groups_config.end();iter++){
  2. Json::Valueclient_dict=(*iter)["clients"];
  3. stringtopic_recresult=(*iter)["topics"]["recresult"].asstring();
  4. stringtopic_recreq=(*iter)["topics"]["recreq"].asstring();
  5. stringtopic_input=(*iter)["topics"]["input"].asstring();
  6. for(Json::ValueIteratorclient_iter=client_dict.begin();client_iter!=client_dict.end();++client_iter){
  7. stringcid=client_iter.key().asstring();
  8. //FIXME:createanewcustomerconfiguration
  9. CustomerPtrc(newCustomer);
  10. c->LoadFromJson(cid,(*client_iter),topic_recresult,topic_recreq,topic_input);
  11. customers[cid]=c;
  12. }
  13. }



2 详细API

    </pre><precode_snippet_id="342950"snippet_file_name="blog_20140513_1_8471295"name="code"class="cpp">classJSONAPI_APIJsonValue
  1. {
  2. typedefstd::map<std::string,JsonValue*>InnerMap;
  3. typedefstd::vector<JsonValue*>InnerVector;
  4. public:
  5. JsonValue();
  6. virtual~JsonValue();
  7. voidclear();
  8. //import/export
  9. voidparse(constchar*jsonString);
  10. JsonStringtoString();
  11. JsonStringtoString_styled();
  12. voidtoFile(char*filename);
  13. voidtoFile_styled(char*filename);
  14. //set
  15. voidoperator=(JsonValue&jval);
  16. voidoperator=(charvInteger);
  17. voidoperator=(unsignedcharvInteger);
  18. shortvInteger);
  19. shortvInteger);
  20. longvInteger);
  21. longvInteger);
  22. intvInteger);
  23. intvInteger);
  24. __int64vInteger);
  25. __int64vInteger);
  26. floatvReal);
  27. doublevReal);
  28. boolvBoolean);
  29. voidoperator=(char*vString);
  30. intappend(JsonValue&jval);
  31. intappend(intappend(unsignedintappend(//get
  32. JsonValue&operator[](char*name);
  33. JsonValue&operator[](unsignedintarrIdx0);
  34. //getfinalvalue
  35. chargetChar();
  36. unsignedchargetUChar();
  37. shortgetShort();
  38. shortgetUShort();
  39. longgetLong();
  40. longgetULong();
  41. intgetInt();
  42. intgetUInt();
  43. __int64getInt64();
  44. __int64getUInt64();
  45. boolgetBoolean();
  46. floatgetFloat();
  47. doublegetDouble();
  48. char*getString();
  49. //check
  50. boolisNull();
  51. boolisChar();
  52. boolisUChar();
  53. boolisShort();
  54. boolisUShort();
  55. boolisLong();
  56. boolisULong();
  57. boolisInt();
  58. boolisUInt();
  59. boolisInt64();
  60. boolisUInt64();
  61. boolisBoolean();
  62. boolisFloat();
  63. boolisDouble();
  64. boolisstring();
  65. boolisObject();
  66. boolisArray();
  67. protected:
  68. ValueTypem_valueType;
  69. union
  70. __int64m_integer;
  71. doublem_real;
  72. boolm_boolean;
  73. char*m_string;
  74. InnerMaP*m_kv;
  75. InnerVector*m_array;
  76. }m_v;
  77. voidsetAsObject();
  78. voidsetAsArray();
  79. friendJValHelper;
  80. };


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工程中在此就不赘述了。先看第一个文件的例

[js] copy
    //JSON文件
  1. {"address":[
  2. {"name":"eliteYang","email":"elite_yang@163.com"},
  3. {"name":"AAA","email":"aaa@163.com"},
  4. {"name":"BBB","email":"bbb@163.com"}
  5. ]}

copy
    /**
  1. *file:jsoncpp_test.cpp
  2. *author:eliteYang
  3. *email:elite_yang@163.com
  4. *blog:http://www.cppfasn.org
  5. *desc:jsoncpptest
  6. */
  7. #include<fstream>
  8. #include<string>
  9. #include"jsoncpp/json.h"
  10. int_tmain(intargc,_TCHAR*argv[])
  11. std::ifstreamifs;
  12. ifs.open("test.json");
  13. Json::Readerreader;
  14. Json::Valueroot;
  15. if(!reader.parse(ifs,root,false))
  16. {return-1;}
  17. Json::Valueadd_value=root["address"];
  18. for(inti=0;i<add_value.size();++i)
  19. {
  20. Json::Valuetemp_value=add_value[i];
  21. std::stringstrName=temp_value["name"].asstring();
  22. std::stringstrMail=temp_value["email"].asstring();
  23. std::cout<<"name:"<<strName<<"email:"<<strMail<<std::endl;
  24. //usevaluearray[index]
  25. //Json::Valuetemp_value=add_value[i];
  26. //std::stringstrName=add_value[i]["name"].asstring();
  27. //std::stringstrMail=add_value[i]["email"].asstring();
  28. //std::cout<<"name:"<<strName<<"email:"<<strMail<<std::endl;
  29. system("Pause");
  30. return0;
  31. }

结果:

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"}

copy
    Json::Value&add_value=root["address"];
  1. Json::Valueappend_value;
  2. append_value["name"]="append";
  3. append_value["email"]="append@163.com";
  4. add_value.append(append_value);
  5. inti=0;i<add_value.size();++i)
  6. Json::Valuetemp_value=add_value[i];
  7. std::stringstrName=temp_value["name"].asstring();
  8. std::stringstrMail=temp_value["email"].asstring();
  9. std::cout<<"name:"<<strName<<"email:"<<strMail<<std::endl;
  10. }
  11. Json::FastWriterwriter;
  12. std::stringjson_append_file=writer.write(root);
  13. std::ofstreamofs;
  14. ofs.open("test_append.json");
  15. ofs<<json_append_file;
  16. 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 请按任意键继续. . .
    copy
      //test_append.json
    1. {"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
    --------------------------------

    相关文章

    AJAX是一种基于JavaScript和XML的技术,能够使网页实现异步交...
    在网页开发中,我们常常需要通过Ajax从后端获取数据并在页面...
    在前端开发中,经常需要循环JSON对象数组进行数据操作。使用...
    AJAX(Asynchronous JavaScript and XML)是一种用于创建 We...
    AJAX技术被广泛应用于现代Web开发,它可以在无需重新加载页面...
    Ajax是一种通过JavaScript和HTTP请求交互的技术,可以实现无...