json解析c實現(c++json解析庫)

本文目錄一覽:

怎麼用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:

其他:

輸出:

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();

}

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

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

相關推薦

  • JSON的MD5

    在Web開發過程中,JSON(JavaScript Object Notation)是最常用的數據格式之一。MD5(Message-Digest Algorithm 5)是一種常用…

    編程 2025-04-29
  • 使用Java將JSON寫入HDFS

    本篇文章將從以下幾個方面詳細闡述Java將JSON寫入HDFS的方法: 一、HDFS簡介 首先,先來了解一下Hadoop分布式文件系統(HDFS)。HDFS是一個可擴展性高的分布式…

    編程 2025-04-29
  • 如何使用Newtonsoft datatable轉Json

    Newtonsoft DataTable 是一個基於.NET的JSON框架,也是一個用於序列化和反序列化JSON的強大工具。 在本文中,我們將學習如何使用Newtonsoft Da…

    編程 2025-04-28
  • JPRC – 輕鬆創建可讀性強的 JSON API

    本文將介紹一個全新的 JSON API 框架 JPRC,通過該框架,您可以輕鬆創建可讀性強的 JSON API,提高您的項目開發效率和代碼可維護性。接下來將從以下幾個方面對 JPR…

    編程 2025-04-27
  • 使用Python獲取JSON並解析

    本文將介紹如何使用Python獲取JSON數據並解析相關內容。通過使用Python的第三方庫,我們可以輕鬆地處理JSON數據,包括讀取、提取和操作JSON數據。 一、獲取JSON數…

    編程 2025-04-27
  • Python存為JSON的方法及實例

    本文將從以下多個方面對Python存為JSON做詳細的闡述。 一、JSON簡介 JSON(JavaScript Object Notation)是一種輕量級的數據交換格式,易於人閱…

    編程 2025-04-27
  • 使用Spread 8展示JSON數據

    使用Spread 8可以方便地展示JSON數據,本文將詳細介紹如何利用Spread 8展示JSON數據。 一、Spread 8簡介 Spread 8是一款強大的電子表格軟件,可以方…

    編程 2025-04-27
  • 如何在json轉實體類時忽略大小寫

    本文將從以下幾個方面介紹如何在json轉實體類時忽略大小寫。 一、使用Gson庫實現json轉實體類忽略大小寫 Gson是Google提供的Java JSON操作庫,它提供了簡單易…

    編程 2025-04-27
  • C# 中 JSON null 不顯示的處理方法

    本文將為大家介紹在 C# 中處理 JSON null 不顯示的解決方法。 一、null 不顯示的問題 在使用 C# 進行 JSON 數據處理的時候,經常會遇到 null 值不顯示的…

    編程 2025-04-27
  • Hive解析JSON詳解

    一、JSON簡介 JSON(JavaScript Object Notation)是一種輕量級的數據交換格式,具有結構清晰、易於讀寫、便於解析等特點。它基於JavaScript的一…

    編程 2025-04-25

發表回復

登錄後才能評論