本文目錄一覽:
如何使用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字元串問題!
一、從字元串中讀取JSON
#include iostream
#include “json/json.h”
using namespace std;
int main()
{
//字元串
const char * str =
“{\”praenomen\”:\”Gaius\”,\”nomen\”:\”Julius\”,\”cognomen\”:\”Caezar\”,”
“\”born\”:-100,\”died\”:-44}” ;
Json::Reader reader;
Json::Value root;
//從字元串中讀取數據
if (reader.parse(str,root))
{
string praenomen = root[ “praenomen” ].asString();
string nomen = root[ “nomen” ].asString();
string cognomen = root[ “cognomen” ].asString();
int born = root[ “born” ].asInt();
int died = root[ “died” ].asInt();
cout praenomen + ” ” + nomen + ” ” + cognomen
” was born in year ” born
“, died in year ” died endl;
}
return 0;
}
makefile文件
LIB=-L /usr/local/lib/libjson/ -ljson_linux- gcc -4.4.7_libmt
a: a.o
g++ -o a -std=c++0x a.o $(LIB)
a.o: a.cpp
g++ -c a.cpp
clean:
rm -rf a.o a
二、從文件中讀取JSON
PersonalInfo.json(一個存儲了JSON格式字元串的文件)
{
“name” : “Tsybius” ,
“age” :23,
“sex_is_male” : true ,
“partner” :
{
“partner_name” : “Galatea” ,
“partner_age” :21,
“partner_sex_is_male” : false
},
“achievement” :[ “ach1” , “ach2” , “ach3” ]
}
#include iostream
#include fstream
#include “json/json.h”
using namespace std;
int main()
{
Json::Reader reader;
Json::Value root;
//從文件中讀取
ifstream is;
is.open( “PersonalInfo.json” , ios::binary);
if (reader.parse(is,root))
{
//讀取根節點信息
string name = root[ “name” ].asString();
int age = root[ “age” ].asInt();
bool sex_is_male = root[ “sex_is_male” ].asBool();
cout “My name is ” name endl;
cout “I’m ” age ” years old” endl;
cout “I’m a ” (sex_is_male ? “man” : “woman” ) endl;
//讀取子節點信息
string partner_name = root[ “partner” ][ “partner_name”].asString();
int partner_age = root[ “partner” ][ “partner_age” ].asInt();
bool partner_sex_is_male = root[ “partner” ][“partner_sex_is_male” ].asBool();
cout “My partner’s name is ” partner_name endl;
cout (partner_sex_is_male ? “he” : “she” ) ” is “
partner_age ” years old” endl;
//讀取數組信息
cout “Here’s my achievements:” endl;
for ( int i = 0; i root[ “achievement” ].size(); i++)
{
string ach = root[ “achievement” ][i].asString();
cout ach ‘\t’ ;
}
cout endl;
cout “Reading Complete!” endl;
}
is.close();
return 0;
}
makefile
?
LIB=-L /usr/local/lib/libjson/ -ljson_linux- gcc -4.4.7_libmt
a: a.o
g++ -o a -std=c++0x a.o $(LIB)
a.o: a.cpp
g++ -c a.cpp
clean:
rm -rf a.o a
三、將信息保存為JSON格式
a.cpp
#include iostream
#include fstream
#include “json/json.h”
using namespace std;
int main()
{
//根節點
Json::Value root;
//根節點屬性
root[ “name” ] = Json::Value( “Tsybius” );
root[ “age” ] = Json::Value(23);
root[ “sex_is_male” ] = Json::Value( true );
//子節點
Json::Value partner;
//子節點屬性
partner[ “partner_name” ] = Json::Value( “Galatea” );
partner[ “partner_age” ] = Json::Value(21);
partner[ “partner_sex_is_male” ] = Json::Value( false );
//子節點掛到根節點上
root[ “partner” ] = Json::Value(partner);
//數組形式
root[ “achievement” ].append( “ach1” );
root[ “achievement” ].append( “ach2” );
root[ “achievement” ].append( “ach3” );
//直接輸出
cout “FastWriter:” endl;
Json::FastWriter fw;
cout fw.write(root) endl endl;
//縮進輸出
cout “StyledWriter:” endl;
Json::StyledWriter sw;
cout sw.write(root) endl endl;
//輸出到文件
ofstream os;
os.open( “PersonalInfo” );
os sw.write(root);
os.close();
return 0;
}
makefile
LIB=-L /usr/local/lib/libjson/ -ljson_linux- gcc -4.4.7_libmt
a: a.o
g++ -o a -std=c++0x a.o $(LIB)
a.o: a.cpp
g++ -c a.cpp
clean:
rm -rf a.o a
{
“achievement” : [ “ach1” , “ach2” , “ach3” ],
“age” : 23,
“name” : “Tsybius” ,
“partner” : {
“partner_age” : 21,
“partner_name” : “Galatea” ,
“partner_sex_is_male” : false
},
“sex_is_male” : true
}
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:
其他:
輸出:
如何讀取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);
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/244425.html