本文目录一览:
如何使用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);