c讀取json文件(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)。

json格式怎麼打開

打開json格式的文件的具體操作步驟如下:

操作設備:聯想拯救者Y9000。

操作系統:Win10專業版。

操作軟體:記事本。

1、首先在電腦的桌面上使用滑鼠右鍵單擊要進行打開的「json」格式的文件,然後在彈出的選項框內點擊「打開方式」選項。

2、接著就會彈出一個對話框,在此對話框內點擊「記事本」選項。

3、接著此時就文件就可以被打開了,在此文件的頁面也可進行對此文件的相關編輯。

json格式的特色:

它基於JavaScript Programming Language, Standard ECMA-262 3rd Edition – December 1999的一個子集。 JSON採用完全獨立於語言的文本格式,但是也使用了類似於C語言家族的習慣。 這些特性使JSON成為理想的數據交換語言。

如何讀取Json文件的數據

var json = { contry:{ area:{ man:”12萬”, women:”10萬” } } };

//方式一:使用eval解析

var obj = eval(json);

alert(obj.constructor);

alert(obj.contry.area.women);

//方式二:使用Funtion函數

var strJSON = “{name:’json name’}”;//得到的JSON

var obj = new Function(“return” + strJSON)();//轉換後的JSON對象

alert(obj.name);//json name

alert(obj.constructor);

//複雜一點的json數組數據的解析

var value1 = [{“c01″:”1″,”c02″:”2″,”c03″:”3″,”c04″:”4″,”c05″:”5″,”c06″:”6″,”c07″:”7″,”c08″:”8″,”c09″:”9”}, {“c01″:”2″,”c02″:”4″,”c03″:”5″,”c04″:”2″,”c05″:”8″,”c06″:”11″,”c07″:”21″,”c08″:”1″,”c09″:”12”}, {“c01″:”5″,”c02″:”1″,”c03″:”4″,”c04″:”11″,”c05″:”9″,”c06″:”8″,”c07″:”1″,”c08″:”8″,”c09″:”2”}]; var obj1 = eval(value1);

alert(obj1[0].c01);

//複雜一點的json的另一種形式

var value2 = {“list”:[ {“password”:”1230″,”username”:”coolcooldool”}, {“password”:”thisis2″,”username”:”okokok”}], “array”:[{“password”:”1230″,”username”:”coolcooldool”},{“password”:”thisis2″,”username”:”okokok”}]};

var obj2 = eval(value2);

alert(obj2.list[0].password);

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

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

原創文章,作者:R2YFG,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/129918.html

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

相關推薦

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

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

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

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

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

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

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

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

    編程 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

發表回復

登錄後才能評論