使用.net 3.5的DataContractJsonSerializer进行JSON Serialization

前端之家收集整理的这篇文章主要介绍了使用.net 3.5的DataContractJsonSerializer进行JSON Serialization前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

可能你看到这个东东的时候还不理解它是什么,但是如果在.net之前的版本你用过JavaScriptSerializer方法的话,应该就明白了,它在.net 3.5中取代了JavaScriptSerialize进行JSON的serialization和deserialization功能

这里举个例子来看,创建一个对象是Person它有FirstName和LastName属性

view plaincopy to clipboardprint?
public class Person
{
public Person() { }
public Person(string firstname,string lastname)
{
this.FirstName = firstname;
this.LastName = lastname;
}
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Person
{
public Person() { }
public Person(string firstname,string lastname)
{
this.FirstName = firstname;
this.LastName = lastname;
}
public string FirstName { get; set; }
public string LastName { get; set; }
}


现在,为了能够让我们的对象通过使用DataContractJsonSerializer转化为JSON,我们需要让为它加上Serializable或者是DataContract属性

view plaincopy to clipboardprint?
public class Person
{
public Person() { }
public Person(string firstname,string lastname)
{
this.FirstName = firstname;
this.LastName = lastname;
}
public string FirstName { get; set; }
public string LastName { get; set; }

}

/// Marked with the DataContact Attribute
[DataContract]
public class Person
{
public Person() { }
public Person(string firstname,string lastname)
{
this.FirstName = firstname;
this.LastName = lastname;
}

[DataMember]
public string FirstName { get; set; }

[DataMember]
public string LastName { get; set; }
}
public class Person
{
public Person() { }
public Person(string firstname,string lastname)
{
this.FirstName = firstname;
this.LastName = lastname;
}
public string FirstName { get; set; }
public string LastName { get; set; }

}

/// Marked with the DataContact Attribute
[DataContract]
public class Person
{
public Person() { }
public Person(string firstname,string lastname)
{
this.FirstName = firstname;
this.LastName = lastname;
}

[DataMember]
public string FirstName { get; set; }

[DataMember]
public string LastName { get; set; }
}

下面的代码是实现Person的serialize。

view plaincopy to clipboardprint?
Person myPerson = new Person("Chris","Pietschmann");

/// Serialize to JSON
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(myPerson.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms,myPerson);
string json = Encoding.Default.GetString(ms.ToArray());
Person myPerson = new Person("Chris","Pietschmann");

/// Serialize to JSON
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(myPerson.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms,myPerson);
string json = Encoding.Default.GetString(ms.ToArray());

如果我们使用的Person对象添加了Serializable属性,那么序列化后的结果如下:

/// Result of Person class marked as Serializable
{"<FirstName>k__BackingField":"Chris","<LastName>k__BackingField":"Pietschmann"}

如果是DataContract属性最后结果为:

/// Result of Person class marked as DataContract with
/// each Property marked as DataMember

{"FirstName":"Chris","LastName":"Pietschmann"}

今天做个东西需要用到json序列化,正好用到这个东西。 不过熟悉generics的话,使用了generics的帮忙让序列化和反序列化都那么容易了。

贴出他的代码,希望大家能够看懂:

view plaincopy to clipboardprint?
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

public class JSONHelper
{
public static string Serialize<T>(T obj)
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms,obj);
string retVal = Encoding.Default.GetString(ms.ToArray());
return retVal;
}

public static T Deserialize<T>(string json)
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
ms.Close();
return obj;
}
}

/// Our Person object to Serialize/Deserialize to JSON
[DataContract]
public class Person
{
public Person() { }
public Person(string firstname,string lastname)
{
this.FirstName = firstname;
this.LastName = lastname;
}

[DataMember]
public string FirstName { get; set; }

[DataMember]
public string LastName { get; set; }
}


/// Sample code using the above helper methods
/// to serialize and deserialize the Person object

Person myPerson = new Person("Chris","Pietschmann");

// Serialize
string json = JSONHelper.Serialize<Person>(myPerson);

// Deserialize
myPerson = JSONHelper.Deserialize<Person>(json);
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

public class JSONHelper
{
public static string Serialize<T>(T obj)
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms,obj);
string retVal = Encoding.Default.GetString(ms.ToArray());
return retVal;
}

public static T Deserialize<T>(string json)
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
ms.Close();
return obj;
}
}

/// Our Person object to Serialize/Deserialize to JSON
[DataContract]
public class Person
{
public Person() { }
public Person(string firstname,string lastname)
{
this.FirstName = firstname;
this.LastName = lastname;
}

[DataMember]
public string FirstName { get; set; }

[DataMember]
public string LastName { get; set; }
}


/// Sample code using the above helper methods
/// to serialize and deserialize the Person object

Person myPerson = new Person("Chris","Pietschmann");

// Serialize
string json = JSONHelper.Serialize<Person>(myPerson);

// Deserialize
myPerson = JSONHelper.Deserialize<Person>(json);

我觉得他挺牛。。。。崇拜中。。。


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/dujingjing1230/archive/2009/08/25/4481386.aspx

"Maximum length exceeded"错误的解决办法

只要修改web.config,在<microsoft.web><scripting><webServices>中定义一下他的长度到足够大就可以了。比如:

<jsonSerialization maxJsonLength="500000"></jsonSerialization>


如:

<system.web.extensions>

<scripting>

<webServices>

<jsonSerializationmaxJsonLength="10240000">

<!--<converters>

<add name="WebService" type="System.Web.Services.WebService"/>

</converters>-->

</jsonSerialization>

<!-- Uncomment this line to customize maxJsonLength and add a custom converter -->

<!--

<jsonSerialization maxJsonLength="500">

<converters>

<add name="ConvertMe" type="Acme.SubAcme.ConvertMeTypeConverter"/>

</converters>

</jsonSerialization>

-->

<!-- Uncomment this line to enable the authentication service. Include requireSSL="true" if appropriate. -->

<!--

<authenticationService enabled="true" requireSSL = "true|false"/>

-->

<!-- Uncomment these lines to enable the profile service. To allow profile properties to be retrieved

and modified in ASP.NET AJAX applications,you need to add each property name to the readAccessProperties and

writeAccessProperties attributes. -->

<!--

<profileService enabled="true"

readAccessProperties="propertyname1,propertyname2"

writeAccessProperties="propertyname1,propertyname2" />

-->

</webServices>

<!--

<scriptResourceHandler enableCompression="true" enableCaching="true" />

-->

</scripting>

</system.web.extensions>

上面设置了:<jsonSerializationmaxJsonLength="10240000">

这是解决ajax传输字节数大于默认值时的设置。


如果对于页面出错配置如下:

<httpRuntime

executionTimeout="1200"

maxRequestLength="102400"

useFullyQualifiedRedirectUrl="false"

minFreeThreads="8"

minLocalRequestFreeThreads="4"

appRequestQueueLimit="100"

/>

猜你在找的Json相关文章