Error during serialization or deserialization using the JSON JavaScriptSerializer

Scope: 

Returning a DataTable from a WebMethod to JavaScript using C#

WebMethod in code behind:

[WebMethod(BufferResponse = false, CacheDuration = 5)]
public static string GetUsers()
{

//Using Subsonic //Replace with your queries to return a dataset
System.Data.DataSet users= DB.Select().From(Tables.Users).ExecuteDataSet();

return users.GetXml();

}

JavaScript:

function getUsersUpdate() {
$.ajax({
type: “POST”,
url: “default.aspx/GetUsers”,
data: ‘{}’,
contentType: “application/json; charset=utf-8”,
dataType: “json”,
success: OnCompleteSuccess,
failure: OnCompleteFailure,
error: OnCompleteError
});
return false;
}

function OnCompleteSuccess(response)
{
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
alert(xml);
}

function OnCompleteFailure(response) {
alert(“Failed: ” + response.reponseText);
}
function OnCompleteError(response) {
alert(“Error Occurred: ” + response.responseText);   //This is where the JSON serialization error is caught
}

Reason for error:

Your DataSet if returning large amount of JSON data while the web.config is configured to allow a max amount of JSON serialization data.

Solution to error:

Remove the max amount of data allowed in the web.config to cater for large amount of JSON data.

In the Web.Config:

Under the <system.web> </system.web> copy and paste the following configs:

<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength=”99999999″/>
</webServices>
</scripting>
</system.web.extensions>

P.S: Make sure that under the <configsection> within the <sectiongroup> you have one section similar to the below:

<section name=”jsonSerialization” type=”System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35″ requirePermission=”false” allowDefinition=”Everywhere”/>

if not, add that too.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s