c# 对象json互相转换_C#中Json格式数据和一些对象的相互转换(序列化和反序列化)...

@序列化:即将类对象或者泛型列表对象转换为json格式。

@反序列化:即将JSON格式数据转换为类对象。

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Runtime.Serialization.Json;

using System.IO;

using System.Text;

using System.Runtime.Serialization.Formatters.Binary;

namespace huoyunxianTest

{

///

///

///

public partial class TestJson2 : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

//声明一个数组格式的json字符串

var txt = @"{""employees"" : [

{ ""firstName"":""Bill"" , ""lastName"":""Gates"" },{ ""firstName"":""George"" , ""lastName"":""Bush"" },

{ ""firstName"":""Thomas"" , ""lastName"":""Carter"" } ]}";

OutClass oc = new OutClass();

List outclass=new List();

oc.employees = outclass;//类型字段赋值

//***************将json数据反序列化为对象,OutClass是对象的类型******************

DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(OutClass));

using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(txt)))

{

----ReadObject以Json格式读取文档流,并返回反序列化对象(即对应的接受类-容器。)

OutClass o1 = ser1.ReadObject(ms) as OutClass;

----下边是将反序列化后得到的对象,写入到对应的泛型类中

foreach (var i in o1.employees)

{

outclass.Add(i);

}

Response.Write(outclass[0].firstName);

Response.Write(outclass[0].lastName);

Response.Write("
*****************************
");

Response.Write("数组序号为0的firstName是:" + o1.employees[0].firstName + "
数组序号为1的firstName是:" + o1.employees[1].firstName + "
数组序号为2的firstName是:" + o1.employees[2].firstName + "
");

Response.Write("数组序号为0的lastName是:" + o1.employees[0].lastName + "
数组序号为1的lastName是:" + o1.employees[1].lastName + "
数组序号为2的lastName是:" + o1.employees[2].lastName);

}

//******************这里是将类型为OutClass的oc对象转换为json格式。*******************

string json3 = GetJSON(oc);

Response.Write(json3);

//******************这里是将类型为InClass的泛型列表outclass转换为json格式。*************

//string json2 = JSON(outclass);

//Response.Write(json2);

}

///

/// 转换对象为JSON格式数据

///

/// 转换对象的类型

/// 待转换对象

/// 字符格式的JSON数据

public static string GetJSON(object obj)

{

string result = String.Empty;

try

{

System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =

new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));

using (System.IO.MemoryStream ms = new System.IO.MemoryStream())

{

serializer.WriteObject(ms, obj);

result = System.Text.Encoding.UTF8.GetString(ms.ToArray());

}

}

catch (Exception ex)

{

throw ex;

}

return result;

}

///

/// 转换List的数据为JSON格式

///

/// 类

/// 列表值

/// JSON格式数据

public static string JSON(List vals)

{

System.Text.StringBuilder st = new System.Text.StringBuilder();

try

{

System.Runtime.Serialization.Json.DataContractJsonSerializer s = new           System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));

foreach (T city in vals)

{

using (System.IO.MemoryStream ms = new System.IO.MemoryStream())

{

s.WriteObject(ms, city);

st.Append(System.Text.Encoding.UTF8.GetString(ms.ToArray()));

}

}

}

catch (Exception ex)

{

throw ex;

}

return st.ToString();

}

}

//备注:C#中对于实体对象的序列化,其实就是字符串拼接。下边的效果和上边的转换效果一样。

StringBuilder sb = new StringBuilder();

sb.Append("[");

foreach (var j in list)

{

if (j != list[list.Count - 1])

{

sb.Append("{\"key\":\"" + j.key + "\",\"value\":\"" + j.value + "\"},");

}

else

{

sb.Append("{\"key\":\"" + j.key + "\",\"value\":\"" + j.value + "\"}");

}

}

sb.Append("]");

return    sb.ToString();

[Serializable]

public class OutClass

{

//上边employees的值是个数组,所以对应用泛型类列表表示。

private List Employees;

public List employees

{

get { return Employees; }

set { Employees = value; }

}

}

[Serializable]

public class InClass

{

private string FirstName;

public string firstName

{

get { return FirstName; }

set { FirstName = value; }

}

private string LastName;

public string lastName

{

get { return LastName; }

set { LastName = value; }

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值