Chinaunix首页 | 论坛 | 博客
  • 博客访问: 411165
  • 博文数量: 155
  • 博客积分: 2590
  • 博客等级: 少校
  • 技术积分: 2161
  • 用 户 组: 普通用户
  • 注册时间: 2012-10-25 09:33
文章分类

全部博文(155)

文章存档

2015年(1)

2014年(2)

2013年(55)

2012年(97)

分类: C/C++

2012-11-26 11:51:59

继续上一篇编译后我们这次来讲怎么配置使用刚生产的lib文件。

1. 在之前的libjson所在的解决方案里新建一个控制台应用程序,叫TestLibjson。

2. 右键TestLibjson项目,选择属性。按下图设置导入libjson的头文件。(虽然我们已经编译成lib库文件,但我们还是要在我们的项目里加入头文件。)


3. 在属性里加入刚刚生产的libjson.lib文件。如下图设置。



好了,配置设置好了,接下来我们写写测试代码

首先新建下列文.h和.cpp文件


在TestLibjson.h文件加入以下代码。

  1. #include "libjson.h"  
  2. class TestLibjson  
  3. {  
  4. public:  
  5.     TestLibjson();  
  6.     void ParseJSON(JSONNODE *n);  
  7. };  

在TestLibjson.cpp文件加入代码。

  1. // TestLibjson.cpp : 定义控制台应用程序的入口点。  
  2. // 
  3.   
  4. #include "stdafx.h"  
  5. #include   
  6. #include "TestLibjson.h"  
  7. #include "libjson.h"  
  8.   
  9. TestLibjson::TestLibjson()//构造函数  
  10. {  
  11. }  
  12.   
  13. void TestLibjson::ParseJSON(JSONNODE *n){//解析json文件  
  14.     if (n == NULL){  
  15.         printf("Invalid JSON Node\n");  
  16.         return;  
  17.     }  
  18.    
  19.     JSONNODE_ITERATOR i = json_begin(n);  
  20.     while (i != json_end(n)){  
  21.         if (*i == NULL){  
  22.             printf("Invalid JSON Node\n");  
  23.             return;  
  24.         }  
  25.    
  26.         // recursively call ourselves to dig deeper into the tree  
  27.         if (json_type(*i) == JSON_ARRAY || json_type(*i) == JSON_NODE){  
  28.             ParseJSON(*i);  
  29.         }  //
  30.    
  31.         // get the node name and value as a string  
  32.         json_char *node_name = json_name(*i);  
  33.    
  34.         // find out where to store the values  
  35.         if (strcmp(node_name, "RootA") == 0){  
  36.             json_char *node_value = json_as_string(*i);  
  37.             printf("rootA: %s\n", node_value);  
  38.             json_free(node_value);  
  39.         }  
  40.         else if (strcmp(node_name, "ChildA") == 0){  
  41.             json_char *node_value = json_as_string(*i);  
  42.             printf("ChildA: %s\n", node_value);  
  43.             json_free(node_value);  
  44.         }  
  45.         else if (strcmp(node_name, "ChildB") == 0)  
  46.             printf("childB: %d\n", json_as_int(*i));  
  47.         // cleanup and increment the iterator  
  48.         json_free(node_name);  
  49.         ++i;  
  50.     }  
  51.     system("pause");  
  52. }  
  53.   
  54. int _tmain()//程序入口  
  55. {  
  56.     char *json = "{\"RootA\":\"Value in parent node\",\"ChildNode\":{\"ChildA\":\"String Value\",\"ChildB\":42}}";  
  57.     JSONNODE *n = json_parse(json);  
  58.     TestLibjson tl = TestLibjson();  
  59.     tl.ParseJSON(n);  
  60.     json_delete(n);  
  61.   
  62.     return 0;  
  63. }  
运行结果


注意,这里我们用的的libjson的Debug模式,如果你用的是release模式,那你还需要设置libOption.h文件,把它的#define JSON_DEBUG 注释掉。

阅读(1214) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~