libjson 编译和使用

以下转自:http://blog.csdn.net/laogong5i0/article/details/8223448

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 <stdlib.h>  
 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
");  
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
");  
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
", 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
", node_value);  
43             json_free(node_value);  
44         }  
45         else if (strcmp(node_name, "ChildB") == 0)  
46             printf("childB: %d
", 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 注释掉。

下一篇:libjson 编译和使用 - 3. libjson的C接口 API

原文地址:https://www.cnblogs.com/fnlingnzb-learner/p/5835516.html