在使用DataContractJsonSerializer进行解析之前,我们首先需要将两个包引入进来:
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
接下来需要新建一个class,DataContractJsonSerializer可以将JSON字符串转化为指定的class或者将class转化为JSON字符串。
这次我接受的JSON数据格式为:
{ "ret": "0", "Isupdate": "1", "Newver": "V1.1.0" }
我们新建的class也要遵照上述格式,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace AutoUpdater_Client.Model
{
//从更新服务器返回的更新信息
[DataContract]
class UpdateInfoJSON
{
//"{ \"ret\": \"0\", \"Isupdate\": \"1\", \"Newver\": \"V1.1.0\" }";
//返回值,为0表示获取信息成功
[DataMember(Order = 0)]
public int ret { get; set; }
//是否需要更新,0表示不需要,1表示需要
[DataMember(Order = 1)]
public int Isupdate { get; set; }
//最新版本号
[DataMember(Order = 2)]
public string Newver { get; set; }
}
}
请注意上述class中的DataContract和DataMember这两个属性,因为DataContractJsonSerializer在进行序列化的时候需要他们,所以一定要记得加上。
另外,这两个属性的使用也需要引入
System.Runtime.Serialization
接下来我们可以来写解析的代码了:
string result = "{ \"ret\": \"0\", \"Isupdate\": \"1\", \"Newver\": \"V1.1.0\" }";
//解析从服务端返回的JSON结果
var mStream = new MemoryStream(Encoding.Default.GetBytes(result));
var serializer = new DataContractJsonSerializer(typeof(UpdateInfoJSON));
UpdateInfoJSON updateInfo = (UpdateInfoJSON)serializer.ReadObject(mStream);
接下来就可以访问updateInfo中的各个属性了,完成。
————————————————
//*************JSON-DataContractJsonSerializer解析
C#中使用JSON不需要使用第三方库,使用.NET Framwork3.5自带的System.Runtime.Serialization.Json即可很好的完成JSON的解析。
关于JSON的入门介绍见(首页的图很形象):
一、Using
需要添加引用:System.ServiceModel.Web 和 System.Runtime.Serialization,然后使用Using:
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
二、定义序列化的类
假如我们要转化的JSON字符串格式为:
{
"encoding":"UTF-8",
"plug-ins":["python","c++","ruby"],
"indent":{
"length":3,
"use_space":true
}
}
然后编写相应的序列化的类,注意下面类加的Attribute:
[DataContract(Namespace = "http://coderzh.cnblogs.com")]
class Config
{
[DataMember(Order = 0)]
public string encoding { get; set; }
[DataMember(Order = 1)]
public string[] plugins { get; set; }
[DataMember(Order = 2)]
public Indent indent { get; set; }
}
[DataContract(Namespace = "http://coderzh.cnblogs.com")]
class Indent
{
[DataMember(Order = 0)]
public int length { get; set; }
[DataMember(Order = 1)]
public bool use_space { get; set; }
}
三、对象转化为JSON字符串
使用WriteObject方法:
var config = new Config(){
encoding = "UTF-8",
plugins = new string[]{"python", "C++", "C#"},
indent = new Indent(){ length = 4, use_space = false}
};
var serializer = new DataContractJsonSerializer(typeof(Config));
var stream = new MemoryStream();
serializer.WriteObject(stream, config);
byte[] dataBytes = new byte[stream.Length];
stream.Position = 0;
stream.Read(dataBytes, 0, (int)stream.Length);
string dataString = Encoding.UTF8.GetString(dataBytes);
Console.WriteLine("JSON string is:");
Console.WriteLine(dataString);
四、JSON字符串转对象
使用ReadObject方法:
ReadObject
五、输出结果:
JSON string is:
{"encoding":"UTF-8","plugins":["python","C++","C#"],"indent":{"length":4,"use_space":false}}
Encoding is: UTF-8
plugins is: python
plugins is: C++
plugins is: C#
indent.length is: 4
indent.use_space is: False
//***********使用List和Json格式相互转化的总结
如Json格式[{"id":"1","name":"sara"},{"id":"2","name":"sara2"}]
自定义数据类型,用于List<>:
[DataContract]
class Person {
[DataMember]
public int id;
[DataMember]
public string name;
}
程序中使用:
首先加入引用:
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.Text;
代码内容:
class Program
{
static void Main(string[] args)
{
//Product.GetAllSmartPhones();
List<Person> nums = new List<Person>();
nums.Add(new Person() {
id=1,
name="sara"
});
nums.Add(new Person() {
id=1,
name="sylar"
});
DataContractJsonSerializer json = new DataContractJsonSerializer(nums.GetType());
string szJson = "";
//序列化
using (MemoryStream stream = new MemoryStream())
{
json.WriteObject(stream, nums);
szJson = Encoding.UTF8.GetString(stream.ToArray());
}
Console.WriteLine(szJson);
Console.ReadLine();
}
}
工程化时,可以对自定义数据结构重新定义一个类:
如:
public class TestListResult<T> : List<T>
{
public TestListResult()
{
this.Successed = false;
this.Message = "";
}
public bool Successed { get; set; }
public string Message { get; set; }
}
使用时同上在一个文件里一样
理解了以上原理,可以使用以下函数在项目中使用:
List<T>转Json
[html] view plaincopy
- public static string Obj2Json<T>(T data)
- {
- try
- {
- System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(data.GetType());
- using (MemoryStream ms = new MemoryStream())
- {
- serializer.WriteObject(ms, data);
- return Encoding.UTF8.GetString(ms.ToArray());
- }
- }
- catch
- {
- return null;
- }
- }
Json转List<T>
[html] view plaincopy
- public static Object Json2Obj(String json,Type t)
- {
- try
- {
- System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(t);
- using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
- {
- return serializer.ReadObject(ms);
- }
- }
- catch
- {
- return null;
- }
- }
DataTable 转Json
[html] view plaincopy
- public static string DataTable2Json(DataTable dt)
- {
- if (dt.Rows.Count == 0)
- {
- return "";
- }
- StringBuilder jsonBuilder = new StringBuilder();
- // jsonBuilder.Append("{");
- //jsonBuilder.Append(dt.TableName.ToString());
- jsonBuilder.Append("[");//转换成多个model的形式
- for (int i = 0; i < dt.Rows.Count; i++)
- {
- jsonBuilder.Append("{");
- for (int j = 0; j < dt.Columns.Count; j++)
- {
- jsonBuilder.Append("\"");
- jsonBuilder.Append(dt.Columns[j].ColumnName);
- jsonBuilder.Append("\":\"");
- jsonBuilder.Append(dt.Rows[i][j].ToString());
- jsonBuilder.Append("\",");
- }
- jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
- jsonBuilder.Append("},");
- }
- jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
- jsonBuilder.Append("]");
- // jsonBuilder.Append("}");
- return jsonBuilder.ToString();
- }
单个对象转JSON
[html] view plaincopy
- public static T Json2Obj<T>(string json)
- {
- T obj = Activator.CreateInstance<T>();
- using (System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(json)))
- {
- System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
- return (T)serializer.ReadObject(ms);
- }
- }
将函数封装成类,更便于项目中引用:
[html] view plaincopy
- public class JsonHelper
- {
- /// <summary>
- /// 生成Json格式
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="obj"></param>
- /// <returns></returns>
- public static string GetJson<T>(T obj)
- {
- DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType());
- using (MemoryStream stream = new MemoryStream())
- {
- json.WriteObject(stream, obj);
- string szJson = Encoding.UTF8.GetString(stream.ToArray());
- return szJson;
- }
- }
- /// <summary>
- /// 获取Json的Model
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="szJson"></param>
- /// <returns></returns>
- public static T ParseFromJson<T>(string szJson)
- {
- T obj = Activator.CreateInstance<T>();
- using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
- {
- DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
- return (T)serializer.ReadObject(ms);
- }
- }
- }
[html] view plaincopy
- /// <summary>
- /// 反回JSON数据到前台
- /// </summary>
- /// <param name="dt">数据表</param>
- /// <returns>JSON字符串</returns>
- public string DataTableToJson(DataTable dt)
- {
- StringBuilder JsonString = new StringBuilder();
- if (dt != null && dt.Rows.Count > 0)
- {
- JsonString.Append("{ ");
- JsonString.Append("\"TableInfo\":[ ");
- for (int i = 0; i < dt.Rows.Count; i++)
- {
- JsonString.Append("{ ");
- for (int j = 0; j < dt.Columns.Count; j++)
- {
- if (j < dt.Columns.Count - 1)
- {
- JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\",");
- }
- else if (j == dt.Columns.Count - 1)
- {
- JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"");
- }
- }
- if (i == dt.Rows.Count - 1)
- {
- JsonString.Append("} ");
- }
- else
- {
- JsonString.Append("}, ");
- }
- }
- JsonString.Append("]}");
- return JsonString.ToString();
- }
- else
- {
- return null;
- }
- }
表的转化Json类:
[html] view plaincopy
- public static class JsonTableHelper
- {
- /// <summary>
- /// 返回对象序列化
- /// </summary>
- /// <param name="obj">源对象</param>
- /// <returns>json数据</returns>
- public static string ToJson(this object obj)
- {
- JavaScriptSerializer serialize = new JavaScriptSerializer();
- return serialize.Serialize(obj);
- }
- /// <summary>
- /// 控制深度
- /// </summary>
- /// <param name="obj">源对象</param>
- /// <param name="recursionDepth">深度</param>
- /// <returns>json数据</returns>
- public static string ToJson(this object obj, int recursionDepth)
- {
- JavaScriptSerializer serialize = new JavaScriptSerializer();
- serialize.RecursionLimit = recursionDepth;
- return serialize.Serialize(obj);
- }
- /// <summary>
- /// DataTable转为json
- /// </summary>
- /// <param name="dt">DataTable</param>
- /// <returns>json数据</returns>
- public static string ToJson(DataTable dt)
- {
- Dictionary<string, object> dic = new Dictionary<string, object>();
- int index = 0;
- foreach (DataRow dr in dt.Rows)
- {
- Dictionary<string, object> result = new Dictionary<string, object>();
- foreach (DataColumn dc in dt.Columns)
- {
- result.Add(dc.ColumnName, dr[dc].ToString());
- }
- dic.Add(index.ToString(), result);
- index++;
- }
- return ToJson(dic);
- }
- }
在Asp.net中前后台Json数据的传递
一、前台产生Json数据传递给后台处理
前台生成Json数据要使用javascript和json.js。
json.js 下载地址:http://www.json.org/json.js
前台代码:
[html] view plaincopy
- var people = [{ "UserName": "t1", "PassWord": "111111", "Sex": "男" },{ "UserName": "t2", "PassWord": "222222", "Sex": "女" }];
- var url = "Default.aspx?people=" + escape(people.toJSONString());
- request.open("POST", url, true);
- request.onreadystatechange = updatePage;
- request.send(null);
后台处理代码:
同上面的转化原理一样,我们先建立一个json数据类,便于List<>中使用。
[html] view plaincopy
- [DataContract]//序列化
- public class TestObj
- {
- [DataMember]
- public string UserName { get; set; }
- [DataMember]
- public string PassWord { get; set; }
- [DataMember]
- public string Sex { get; set; }
- public TestObj(string u,string p,string s)
- {
- UserName = u;
- PassWord = p;
- Sex = s;
- }
- }
对前台提交的Json数据相互转化函数
[html] view plaincopy
- //json 序列化
- public static string ToJsJson(object item)
- {
- DataContractJsonSerializer serializer = new DataContractJsonSerializer(item.GetType());
- using(MemoryStream ms=new MemoryStream())
- {
- serializer.WriteObject(ms, item);
- StringBuilder sb = new StringBuilder();
- sb.Append(Encoding.UTF8.GetString(ms.ToArray()));
- return sb.ToString();
- }
- }
- //反序列化
- public static T FromJsonTo<T>(string jsonString)
- {
- DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
- using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
- {
- T jsonObject = (T)ser.ReadObject(ms);
- return jsonObject;
- }
- }
在后台代码中调用以上函数进行对数据people的处理:
[html] view plaincopy
- //获取json字符串
- string jsonStr = Request["people"];
- List<TestObj> obj = Json.FromJsonTo<List<TestObj>>(jsonStr);
- foreach (TestObj item in obj)
- {
- Response.Write(string.Format("UserName:{0},Password:{1},Sex:{2}/r/n", item.UserName, item.PassWord, item.Sex));
- }
- Response.End();
最终的结果:
[html] view plaincopy
- List<TestObj> Users = new List<TestObj>();
- Users.Add(new TestObj("t1", "1", "男"));
- Users.Add(new TestObj("t2", "2", "女"));
- string json = Json.ToJsJson(Users);
- Response.Write(json);
- Response.End();
二、前台获取后台提交的Json数据
后台产生Json数据的方法如上原理中提到的:
[html] view plaincopy
- string Json;
- DataContractJsonSerializer json = new DataContractJsonSerializer(list.GetType());
- using (MemoryStream stream = new MemoryStream())
- {
- json.WriteObject(stream, list);
- Json = Encoding.UTF8.GetString(stream.ToArray());
- }
- return Json;
[html] view plaincopy
- /// <summary>
- /// Json的数据结构
- /// </summary>
- [DataContract]
- class ResultJson
- {
- [DataMember]
- public bool Result;
- [DataMember]
- public int Count;
- [DataMember]
- public string Message;
- }
前台获取后台返回的Json字符串:
[html] view plaincopy
- function updatePage() {
- if (request.readyState == 4) {
- if (request.status == 200) {
- var response = request.responseText;
- //转化成对象
- //方法1
- response = response.parseJSON();
- //方法2
- // response = eval("(" + response + ")");
- //对象访问方式
- document.getElementById("d1").innerHTML = response[1].Sex;
- //直接输出
- // document.getElementById("d1").innerHTML = response;
- }
- }
- }
复杂的Json字符串操作方法:
假如我们要转化的JSON字符串格式为:
[html] view plaincopy
- {
- "encoding":"UTF-8",
- "plug-ins":["python","c++","ruby"],
- "indent":{
- "length":3,
- "use_space":true
- }
- }
然后编写相应的序列化的类,注意下面Indent类加的属性:
[html] view plaincopy
- [DataContract]
- class Config
- {
- [DataMember(Order = 0)]
- public string encoding { get; set; }
- [DataMember(Order = 1)]
- public string[] plugins { get; set; }
- [DataMember(Order = 2)]
- public Indent indent { get; set; }
- }
- [DataContract]
- class Indent
- {
- [DataMember(Order = 0)]
- public int length { get; set; }
- [DataMember(Order = 1)]
- public bool use_space { get; set; }
- }
输出JSON字符串
[html] view plaincopy
- var config = new Config(){
- encoding = "UTF-8",
- plugins = new string[]{"python", "C++", "C#"},
- indent = new Indent(){ length = 4, use_space = false}
- };
- var serializer = new DataContractJsonSerializer(typeof(Config));
- var stream = new MemoryStream();
- serializer.WriteObject(stream, config);
- byte[] dataBytes = new byte[stream.Length];
- stream.Position = 0;
- stream.Read(dataBytes, 0, (int)stream.Length);
- string dataString = Encoding.UTF8.GetString(dataBytes);
- Console.WriteLine("JSON string is:");
- Console.WriteLine(dataString);
结果:
[html] view plaincopy
- JSON string is:
- {"encoding":"UTF-8","plugins":["python","C++","C#"],"indent":{"length":4,"use_space":false}}
读取Json字符串内容:
[html] view plaincopy
- var mStream = new MemoryStream(Encoding.Default.GetBytes(dataString));
- Config readConfig = (Config)serializer.ReadObject(mStream);
- Console.WriteLine("Encoding is: {0}", readConfig.encoding);
- foreach (string plugin in readConfig.plugins)
- {
- Console.WriteLine("plugins is: {0}", plugin);
- }
- Console.WriteLine("indent.length is: {0}", readConfig.indent.length);
- Console.WriteLine("indent.use_space is: {0}", readConfig.indent.use_space);
结果:
[html] view plaincopy
- Encoding is: UTF-8
- plugins is: python
- plugins is: C++
- plugins is: C#
- indent.length is: 4
- indent.use_space is: False
来源:oschina
链接:https://my.oschina.net/u/4418004/blog/4375182