DataContractJsonSerializer 类 操作json类型数据

前端之家收集整理的这篇文章主要介绍了DataContractJsonSerializer 类 操作json类型数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

将对象序列化为 JavaScript 对象表示法 (JSON),并将 JSON 数据反序列化为对象。 此类不能继承。

//  msdn 例子:

namespace SL_DataContractJsonSerializer
{
public partial class Page:UserControl
{
public Page()
{
InitializeComponent();
}

// Thisusesaneventhandler,notSLdatabinding
void OnClick( object sender,EventArgsargs)
{
txtOutput1.Text
= " CreateaUserobjectandserializeit. " ;
string json = WriteFromObject();
txtOutput2.Text
= json.ToString(); Displays:{"Age":42,"Name":"Bob"}

txtOutput3.Text
= DeserializethedatatoaUserobject. string jsonString = {'Name':'Bill','Age':53} " ;
UserdeserializedUser
= ReadToObject(jsonString);
txtOutput4.Text
= deserializedUser.Name; Displays:Bill
txtOutput5.Text = deserializedUser.Age.ToString(); Displays:53
}
CreateaUserobjectandserializeittoaJSONstream. static string WriteFromObject()
{
CreateUserobject.
Useruser = new User( Bob " , 42 );

Createastreamtoserializetheobjectto.
MemoryStreamms = new MemoryStream();

SerializertheUserobjecttothestream.
DataContractJsonSerializerser = new DataContractJsonSerializer( typeof (User));
ser.WriteObject(ms,user);
byte []json = ms.ToArray();
ms.Close();
return Encoding.UTF8.GetString(json,128); line-height:1.5!important">0 ,json.Length);

}

DeserializeaJSONstreamtoaUserobject. static UserReadToObject( string json)
{
UserdeserializedUser
= new User();
MemoryStreamms
= new MemoryStream(Encoding.UTF8.GetBytes(json));
DataContractJsonSerializerser
= new DataContractJsonSerializer(deserializedUser.GetType());
deserializedUser
= ser.ReadObject(ms) as User;
ms.Close();
return deserializedUser;
}

}

[DataContract]
class User
{
[DataMember]
string Name{ get ; set ;}

[DataMember]
int Age{ set ;}

public User(){}

public User( string newName, int newAge)
{
Name
= newName;
Age
= newAge;
}

}

}


可以抽象成如下类:

public class JsonHelper
{
/// <summary>
生成Json格式
</summary> <typeparamname="T"></typeparam> <paramname="obj"></param> <returns></returns>
static string GetJson < T > (Tobj)
{
DataContractJsonSerializerjson
= new DataContractJsonSerializer(obj.GetType());
using (MemoryStreamstream = new MemoryStream())
{
json.WriteObject(stream,obj);
string szJson = Encoding.UTF8.GetString(stream.ToArray());
return szJson;
}
}
获取Json的Model
<paramname="szJson"></param> static TParseFromJson < T > ( string szJson)
{
Tobj
= Activator.CreateInstance < T > ();
using (MemoryStreamms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
{
DataContractJsonSerializerserializer
= return (T)serializer.ReadObject(ms);
}
}
}
反回JSON数据到前台
<paramname="dt"> 数据表 </param> <returns> JSON字符串 </returns> string DataTableToJson(DataTabledt)
{
StringBuilderJsonString
= 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(
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 - "" );
}
}
if (i == dt.Rows.Count - } else
{
JsonString.Append(
},0); line-height:1.5!important">" );
}
}
JsonString.Append(
]} return JsonString.ToString();
}
else
{
return null ;
}
}

//还有一种方式操作json类型数据:

class JsonTableHelper
{
返回对象序列化
<paramname="obj"> 源对象 json数据 </returns> string ToJson( this object obj)
{
JavaScriptSerializerserialize
= new JavaScriptSerializer();
return serialize.Serialize(obj);
}

控制深度
<paramname="recursionDepth"> 深度 object obj, int recursionDepth)
{
JavaScriptSerializerserialize
= new JavaScriptSerializer();
serialize.RecursionLimit
= recursionDepth;
DataTable转为json
DataTable string ToJson(DataTabledt)
{
Dictionary
< string ,255); line-height:1.5!important">object > dic = new Dictionary < object > ();

int index = 0 ;
foreach (DataRowdr in dt.Rows)
{
Dictionary
< object > result = foreach (DataColumndc in dt.Columns)
{
result.Add(dc.ColumnName,dr[dc].ToString());
}
dic.Add(index.ToString(),result);
index
++ ;
}
return ToJson(dic);
}
}
原文链接:https://www.f2er.com/json/290350.html

猜你在找的Json相关文章