首页 > 编程知识 正文

c读取json文件(c#读取json文件的内容)

时间:2023-12-13 14:15:34 阅读:315124 作者:ZDSC

本文目录一览:

怎么用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 : %sn", pSub-valuestring);

// get number from json

pSub = cJSON_GetObjectItem(pJson, "number");

if(NULL == pSub)

{

//get number from json faild

}

printf("obj_2 : %dn", pSub-valueint);

// get bool from json

pSub = cJSON_GetObjectItem(pJson, "bool");

if(NULL == pSub)

{

// get bool from json faild

}

printf("obj_3 : %dn", 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 : %sn", pSubSub-valuestring);

cJSON_Delete(pJson);

}

int main()

{

char * p = makeJson();

if(NULL == p)

{

return 0;

}

printf("%sn", 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 faildn");

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数据,保存到一个数组里面就行了

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。