本文目錄一覽:
怎麼用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