c中讀取json文件(c++解析json文件)

本文目錄一覽:

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數據

直接文件操作就行了。fopen,然後直接讀出文件中的json數據,保存到一個數組裏面就行了

c#讀取json

先聲明,以下兩個方法我一直用

肯定沒有問題

TXT讀取方法

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.IO;

namespace WindowsApplication1

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

private void Form1_Load(object sender, EventArgs e)

{

this.rT1.Text = “”;

FileStream fs1 = new FileStream(“2.txt”, FileMode.Open);

StreamReader sr = new StreamReader(fs1);

string str1 = sr.ReadToEnd();

this.rT1.Text = str1;

sr.Close();

fs1.Close();

}

}

}

———————————————————————————-

以下是 json的 序列化和反序列化

.net3.5提供了json對象序列化與反序列化的類。位置在:System.Runtime.Serialization.Json空間下。其中如果要應用這個空間還必須添加對

System.ServiceModel

System.ServiceModel.Web

這兩個庫文件的引用。

參考實體類:Customer

public class Customer

{

public int Unid { get; set; }

public string CustomerName { get; set; }

}

DataContractJsonSerializer

將對象序列化為 JavaScript 對象表示法 (JSON),並將 JSON 數據反序列化為對象。無法繼承此類。

其中有個方法WriteObject,它的功能定義為:將對象序列化為 JavaScript 對象表示法 (JSON) 文檔

它有三個方法重載,其中一個為:

public override void WriteObject(Stream stream,Object graph)

它的功能描述這:將指定對象序列化為 JavaScript 對象表示法 (JSON) 數據,並將生成的 JSON 寫入流中

(一)序列化

public string ToJson(Customer customer)

{

DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(Customer));

MemoryStream ms=new MemoryStream();

ds.WriteObject(ms, customer);

string strReturn=Encoding.UTF8.GetString(ms.ToArray());

ms.Close();

return strReturn;

}

創建類實例,通過它的WriteObject方法來向流寫入序列化的對象,再把流寫入到字符串中。就可以得到JSON對象。

測試一下:

Customer cc = new Customer {Unid=1,CustomerName=”John” };

string strJson = ToJson(cc);

Console.WriteLine(strJson);

結果為:{“CustomerName”:”John”,”Unid”:1}

(二)反序列化

ReadObject方法,其描述為:反序列化 JSON(JavaScript 對象表示法)數據,並返回反序列化的對象。

它有很多重載,現在通過一種:

public override Object ReadObject(Stream stream)

它從流中得到反序列化的對象。

public object FromJson(string strJson)

{

DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(Customer));

MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strJson));

return ds.ReadObject(ms);

}

測試:

string strJson=”{\”CustomerName\”:\”John\”,\”Unid\”:1}”;

Customer c=FromJson(strJson) as Customer;

Console.WriteLine(c.Unid+” “+c.CustomerName);

(三)通過泛型方法對兩者進行修改

為了適應多類型實例的序列化與反序列化,通過泛型方法來實現。

public string ToJsonT(T t)

{

DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(T));

MemoryStream ms = new MemoryStream();

ds.WriteObject(ms, t);

string strReturn = Encoding.UTF8.GetString(ms.ToArray());

ms.Close();

return strReturn;

}

public T FromJsonT(string strJson) where T:class

{

DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(T));

MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strJson));

return ds.ReadObject(ms) as T;

}

•反序列化時通過泛型約束來指定類型T為類類型。

測試:

Customer cc = new Customer {Unid=1,CustomerName=”John” };

string strJsons = ToJsonCustomer(cc);

Console.WriteLine(strJsons);

string strJson=”{\”CustomerName\”:\”John\”,\”Unid\”:1}”;

Customer c = FromJsonCustomer(strJson);

Console.WriteLine(c.Unid+” “+c.CustomerName);

怎麼用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)。

JSON解析器json-c

JSON-C實現了一個引用計數對象模型,它允許您輕鬆地使用C語言來構建JSON對象,將它們輸出為JSON格式的字符串,並將JSON格式字符串解析回JSON對象的C語言表示形式。它的目標是符合 RFC 7159 標準。

使用automake的編譯過程如下:

使用cmake編譯的過程如下:

cmake可選的幾個編譯選項為:

要使用json-c,最簡單的方式是包含json.h頭文件即可,或者最好是下列更具體的頭文件之一:

詳細且全面的API介紹文檔:

JSON-C支持的JSON對象類型有7種:

下面系列函數用於創建一個JSON對象:

給JSON對象增加字段(不會增加引用計數):

刪除json對象的指定字段,被刪除的對象引用計數減去1,如果這個val沒有更多的所有者,這個key對應的val被free,否則這個val的引用保存在內存中:

增加一個元素到json數組的末尾,obj引用計數不會增加,增加字段的方式更加緊湊;如果需要獲取val的引用,需要用json_object_get()來傳遞該對象:

替換json數組中的值:

json數組的排序,這裡需要自己寫排序函數:

獲取json對象的長度,依據字段的數目:

獲取json對象的哈希表:

獲取對象的數組列表:

獲取json的類型:

獲取json數組對象的長度:

獲取json對象的bool值,int和double對象是0轉換為FALSE,否則返回TRUE;非0長度的字符串返回TRUE;其他對象非空的話,返回TRUE:

獲取json對象的長度,如果參數不是string類型的json,返回0:

按照索引獲取json數組的對象:

轉換json對象到c字符串格式:

獲取JSON中指定類型的數值:

將字符串轉換為json對象:

以下兩個函數配合使用,前者獲取該對象指針的所有權,引用計數加1,如果對象已經被釋放,返回NULL;後者引用計數減1,如果對象已經被釋放,返回1:

類型判斷:

json_util.h提供了有關文件讀寫操作的函數,這個文件的內容是json格式的:

原創文章,作者:簡單一點,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/130566.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
簡單一點的頭像簡單一點
上一篇 2024-10-03 23:29
下一篇 2024-10-03 23:29

相關推薦

  • vue下載無後綴名的文件被加上後綴.txt,有後綴名的文件下載正常問題的解決

    本文旨在解決vue下載無後綴名的文件被加上後綴.txt,有後綴名的文件下載正常的問題,提供完整的代碼示例供參考。 一、分析問題 首先,需了解vue中下載文件的情況。一般情況下,我們…

    編程 2025-04-29
  • 如何在Java中拼接OBJ格式的文件並生成完整的圖像

    OBJ格式是一種用於表示3D對象的標準格式,通常由一組頂點、面和紋理映射坐標組成。在本文中,我們將討論如何將多個OBJ文件拼接在一起,生成一個完整的3D模型。 一、讀取OBJ文件 …

    編程 2025-04-29
  • Python程序文件的拓展

    Python是一門功能豐富、易於學習、可讀性高的編程語言。Python程序文件通常以.py為文件拓展名,被廣泛應用於各種領域,包括Web開發、機器學習、科學計算等。為了更好地發揮P…

    編程 2025-04-29
  • Python中讀入csv文件數據的方法用法介紹

    csv是一種常見的數據格式,通常用於存儲小型數據集。Python作為一種廣泛流行的編程語言,內置了許多操作csv文件的庫。本文將從多個方面詳細介紹Python讀入csv文件的方法。…

    編程 2025-04-29
  • 為什麼用cmd運行Java時需要在文件內打開cmd為中心

    在Java開發中,我們經常會使用cmd在命令行窗口運行程序。然而,有時候我們會發現,在運行Java程序時,需要在文件內打開cmd為中心,這讓很多開發者感到疑惑,那麼,為什麼會出現這…

    編程 2025-04-29
  • Python zipfile解壓文件亂碼處理

    本文主要介紹如何在Python中使用zipfile進行文件解壓的處理,同時詳細討論在解壓文件時可能出現的亂碼問題的各種解決辦法。 一、zipfile解壓文件亂碼問題的根本原因 在P…

    編程 2025-04-29
  • Python將矩陣存為CSV文件

    CSV文件是一種通用的文件格式,在統計學和計算機科學中非常常見,一些數據分析工具如Microsoft Excel,Google Sheets等都支持讀取CSV文件。Python內置…

    編程 2025-04-29
  • Python如何導入py文件

    Python是一種開源的高級編程語言,因其易學易用和強大的生態系統而備受青睞。Python的import語句可以幫助用戶將一個模塊中的代碼導入到另一個模塊中,從而實現代碼的重用。本…

    編程 2025-04-29
  • Python合併多個相同表頭文件

    對於需要合併多個相同表頭文件的情況,我們可以使用Python來實現快速的合併。 一、讀取CSV文件 使用Python中的csv庫讀取CSV文件。 import csv with o…

    編程 2025-04-29
  • Python寫文件a

    Python語言是一種功能強大、易於學習、通用並且高級編程語言,它具有許多優點,其中之一就是能夠輕鬆地進行文件操作。文件操作在各種編程中都佔有重要的位置,Python作為開發人員常…

    編程 2025-04-29

發表回復

登錄後才能評論