cjsonobject用法,cjproject

本文目錄一覽:

C++ json解析

C++ 解析Json——jsoncpp

JSON(JavaScript Object Notation) 是一種輕量級的數據交換格式,和xml類似,本文主要對VS2008中使用Jsoncpp解析json的方法做一下記錄。

Jsoncpp是個跨平台的開源庫,下載地址:,我下載的是v0.5.0,壓縮包大約104K。

方法一:使用Jsoncpp生成的lib文件

解壓上面下載的Jsoncpp文件,在jsoncpp-src-0.5.0/makefiles/vs71目錄里找到jsoncpp.sln,用VS2008版本編譯,默認生成靜態鏈接庫。 在工程中引用,只需要包含include/json下的頭文件及生成的.lib文件即可。

如何包含lib文件:在.cpp文件中#pragma comment(lib.”json_vc71_libmt.lib”),在工程屬性中Linker下Input中Additional Dependencies寫入lib文件名字(Release下為json_vc71_libmt.lib,Debug為json_vc71_libmtd.lib)

注意:Jsoncpp的lib工程編譯選項要和VS工程中的編譯選項保持一致。如lib文件工程編譯選項為MT(或MTd),VS工程中也要選擇MT(或MTd),否則會出現編譯錯誤問題,debug和release下生成的lib文件名字不同,注意不要看錯了,當成一個文件來使用(我就犯了這個錯誤)。

方法二:使用Jsoncpp包中的.cpp和.h文件

解壓上面下載的Jsoncpp文件,把jsoncpp-src-0.5.0文件拷貝到工程目錄下,將jsoncpp-src-0.5.0\jsoncpp-src-0.5.0\include\json和jsoncpp-src-0.5.0\jsoncpp-src-0.5.0\src\lib_json目錄里的文件包含到VS工程中,在VS工程的屬性C/C++下General中Additional Include Directories包含頭文件目錄.\jsoncpp-src-0.5.0\include。在使用的cpp文件中包含json頭文件即可,如:#include “json/json.h”。將json_reader.cpp、json_value.cpp和json_writer.cpp三個文件的Precompiled Header屬性設置為Not Using Precompiled Headers,否則編譯會出現錯誤。

jsoncpp 使用詳解

jsoncpp 主要包含三種類型的 class:Value、Reader、Writer。jsoncpp 中所有對象、類名都在 namespace Json 中,包含 json.h 即可。

Json::Value 只能處理 ANSI 類型的字符串,如果 C++ 程序是用 Unicode 編碼的,最好加一個 Adapt 類來適配。

下面是從網上找的代碼示例:

1. 從字符串解析json

const char* str = “{\”uploadid\”: \”UP000000\”,\”code\”: 100,\”msg\”: \”\”,\”files\”: \”\”}”;

Json::Reader reader;

Json::Value root;

if (reader.parse(str, root)) // reader將Json字符串解析到root,root將包含Json里所有子元素

{

std::string upload_id = root[“uploadid”].asString(); // 訪問節點,upload_id = “UP000000”

int code = root[“code”].asInt(); // 訪問節點,code = 100

}

2. 從文件解析json

int ReadJsonFromFile(const char* filename)

{

Json::Reader reader;// 解析json用Json::Reader

Json::Value root; // Json::Value是一種很重要的類型,可以代表任意類型。如int, string, object, array

std::ifstream is;

is.open (filename, std::ios::binary );

if (reader.parse(is, root, FALSE))

{

std::string code;

if (!root[“files”].isNull()) // 訪問節點,Access an object value by name, create a null member if it does not exist.

code = root[“uploadid”].asString();

code = root.get(“uploadid”, “null”).asString();// 訪問節點,Return the member named key if it exist, defaultValue otherwise.

int file_size = root[“files”].size(); // 得到”files”的數組個數

for(int i = 0; i file_size; ++i) // 遍曆數組

{

Json::Value val_image = root[“files”][i][“images”];

int image_size = val_image.size();

for(int j = 0; j image_size; ++j)

{

std::string type = val_image[j][“type”].asString();

std::string url = val_image[j][“url”].asString();

printf(“type : %s, url : %s \n”, type.c_str(), url.c_str());

}

}

}

is.close();

return 0;

}

3. 向文件中插入json

void WriteJsonData(const char* filename)

{

Json::Reader reader;

Json::Value root; // Json::Value是一種很重要的類型,可以代表任意類型。如int, string, object, array

std::ifstream is;

is.open (filename, std::ios::binary );

if (reader.parse(is, root))

{

Json::Value arrayObj; // 構建對象

Json::Value new_item, new_item1;

new_item[“date”] = “2011-11-11”;

new_item1[“time”] = “11:11:11”;

arrayObj.append(new_item); // 插入數組成員

arrayObj.append(new_item1); // 插入數組成員

int file_size = root[“files”].size();

for(int i = 0; i file_size; ++i)

root[“files”][i][“exifs”] = arrayObj; // 插入原json中

std::string out = root.toStyledString();

// 輸出無格式json字符串

Json::FastWriter writer;

std::string strWrite = writer.write(root);

std::ofstream ofs;

ofs.open(“test_write.json”);

ofs strWrite;

ofs.close();

}

is.close();

}

誰給推薦一個C++的JSON庫

jsoncpp、還有cJSON,推薦cJSON這個輕量級的JSON庫,它使用起來非常簡單,只需要把cJSON.c和cJSON.h兩個文件複製到你的項目中就可以了,使用時#include “cJSON.h”。cJSON可以在github上下載,github上還有一段簡單的使用說明,cJSON庫可以解析JSON,也可以生成JSON文件,用cJSON一般只用寫4、5行代碼(所以說它的輕量級的)。

怎麼用C語言獲取JSON中的數據?

用C語言獲取JSON中的數據的方法是使用 CJSON。

以下簡單介紹用CJSON的思路及實現:

1)創建json,從json中獲取數據。

#nclude stdio.h

#include “cJSON.h”

char * makeJson()

{

cJSON * pJsonRoot = NULL;

pJsonRoot = cJSON_CreateObject();

if(NULL == pJsonRoot)

{

//error happend here

return NULL;

}

cJSON_AddStringToObject(pJsonRoot, “hello”, “hello world”);

cJSON_AddNumberToObject(pJsonRoot, “number”, 10010);

cJSON_AddBoolToObject(pJsonRoot, “bool”, 1);

cJSON * pSubJson = NULL;

pSubJson = cJSON_CreateObject();

if(NULL == pSubJson)

{

// create object faild, exit

cJSON_Delete(pJsonRoot);

return NULL;

}

cJSON_AddStringToObject(pSubJson, “subjsonobj”, “a sub json string”);

cJSON_AddItemToObject(pJsonRoot, “subobj”, pSubJson);

char * p = cJSON_Print(pJsonRoot);

// else use :

// char * p = cJSON_PrintUnformatted(pJsonRoot);

if(NULL == p)

{

//convert json list to string faild, exit

//because sub json pSubJson han been add to pJsonRoot, so just delete pJsonRoot, if you also delete pSubJson, it will coredump, and error is : double free

cJSON_Delete(pJsonRoot);

return NULL;

}

//free(p);

cJSON_Delete(pJsonRoot);

return p;

}

void parseJson(char * pMsg)

{

if(NULL == pMsg)

{

return;

}

cJSON * pJson = cJSON_Parse(pMsg);

if(NULL == pJson)

{

// parse faild, return

return ;

}

// get string from json

cJSON * pSub = cJSON_GetObjectItem(pJson, “hello”);

if(NULL == pSub)

{

//get object named “hello” faild

}

printf(“obj_1 : %s\n”, pSub-valuestring);

// get number from json

pSub = cJSON_GetObjectItem(pJson, “number”);

if(NULL == pSub)

{

//get number from json faild

}

printf(“obj_2 : %d\n”, pSub-valueint);

// get bool from json

pSub = cJSON_GetObjectItem(pJson, “bool”);

if(NULL == pSub)

{

// get bool from json faild

}

printf(“obj_3 : %d\n”, pSub-valueint);

// get sub object

pSub = cJSON_GetObjectItem(pJson, “subobj”);

if(NULL == pSub)

{

// get sub object faild

}

cJSON * pSubSub = cJSON_GetObjectItem(pSub, “subjsonobj”);

if(NULL == pSubSub)

{

// get object from subject object faild

}

printf(“sub_obj_1 : %s\n”, pSubSub-valuestring);

cJSON_Delete(pJson);

}

int main()

{

char * p = makeJson();

if(NULL == p)

{

return 0;

}

printf(“%s\n”, p);

parseJson(p);

free(p);//這裡不要忘記釋放內存,cJSON_Print()函數或者cJSON_PrintUnformatted()產生的內存,使用free(char *)進行釋放

return 0;

}

2)創建json數組和解析json數組

//創建數組,數組值是另一個JSON的item,這裡使用數字作為演示

char * makeArray(int iSize)

{

cJSON * root = cJSON_CreateArray();

if(NULL == root)

{

printf(“create json array faild\n”);

return NULL;

}

int i = 0;

for(i = 0; i iSize; i++)

{

cJSON_AddNumberToObject(root, “hehe”, i);

}

char * out = cJSON_Print(root);

cJSON_Delete(root);

return out;

}

//解析剛剛的CJSON數組

void parseArray(char * pJson)

{

if(NULL == pJson)

{

return ;

}

cJSON * root = NULL;

if((root = cJSON_Parse(pJson)) == NULL)

{

return ;

}

int iSize = cJSON_GetArraySize(root);

for(int iCnt = 0; iCnt iSize; iCnt++)

{

cJSON * pSub = cJSON_GetArrayItem(root, iCnt);

if(NULL == pSub)

{

continue;

}

int iValue = pSub-valueint;

printf(“value[%2d] : [%d]\n”, iCnt, iValue);

}

cJSON_Delete(root);

return;

}

有兩種方法:

一是標準的輸出輸入方式 比如新建一個磁盤文件c:\a.txt, 將鍵盤輸入的一字符串寫到文件中:

FILE *ft;

char str[50];

ft=fopen(“c:\\a.txt”,”w+”);

printf(“輸入一個字符串:”);

scanf(“%s”,str);

fputs(str,ft);

fclose(ft);

//重新打開這個文件並讀出字符串,顯示在屏幕上 ft=fopen(“c:\\a.txt”,”rt”);

fgets(str,50,ft);

fclose(ft); printf(“%s”,str);

二是低級輸入輸出方式 仍如上例:

int hd; char str[50]; printf(“輸入一個字符串:”);

scanf(“%s”,str);

hd=open(“c:\\a.txt”,O_CREAT|O_TEXT|O_WRONLY);

write(hd,str,strlen(str));

close(hd); //重新打開這個文件並讀出字符串,顯示在屏幕上。

hd=open(“c:\\a.txt”,O_TEXT|O_RDONLY); read(hd,str,50);

close(hd); printf(“%s”,str)。

c#解析JSON的幾種辦法

對比

準備數據

實體類:

定義:

使用DataContractJsonSerializer

幫助類:

用法:

輸出:

使用JavaScriptSerializer

// using System.Web.Script.Serialization;

   

 

var jser    = new JavaScriptSerializer();

 

var json    = jser.Serialize(new ListPerson() { p1, p2 });

 

var persons = jser.DeserializeListPerson(json);

使用Silverlight

使用JSON.NET

輸出:

LINQ:

其他:

輸出:

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/235922.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-12 11:57
下一篇 2024-12-12 11:57

相關推薦

發表回復

登錄後才能評論