PDA

View Full Version : Getting error: Unable to parse the JSON returned by the server:



ppatel2
28 Feb 2012, 12:31 PM
Hi,

I am new to ExtJS. I am trying to create a grid with the data coming from ASP.NET web services. I am receiving Json error and not able to figure out how to solve it. Can anyone help me out ?

Here is my code.

ExtJS code:

Ext.onReady(function() {

var sampleGridReader = new Ext.data.JsonReader({
idProperty: 'AddressID',
root: 'Table'
}, [
{ name: 'AddressID' },
{ name: 'AddressLine1' },
{ name: 'AddressLine2' },
{ name: 'City' },
{ name: 'StateProvince' },
{ name: 'CountryRegion' },
{ name: 'PostalCode' },
{ name: 'rowguid' },
{ name: 'ModifiedDate' }
]);




// create the data store
var store = new Ext.data.Store({
autoLoad: true,
proxy:{
type:'ajax',
url: 'http://localhost:52215/Website1/WebService.asmx/GetData',
headers: {'Content-type':'application/json; charset=utf-8'},
reader: sampleGridReader
},
});


// create the Grid
var grid = new Ext.grid.GridPanel({
store: store,
columns: [
{
header:'AddressID',
dataIndex: 'AddressID'
},
{
header:'AddressLine1',
dataIndex: 'AddressLine1'
},
{
header:'AddressLine2',
dataIndex: 'AddressLine2'
},
{
header:'City',
dataIndex: 'City'
},
{
header:'StateProvince',
dataIndex: 'StateProvince'
},
{
header:'CountryRegion',
dataIndex: 'CountryRegion'
},
{
header:'PostalCode',
dataIndex: 'PostalCode'
},
{
header:'rowguid',
dataIndex: 'rowguid'
},
{
header:'ModifiedDate',
dataIndex: 'ModifiedDate'
}
],
height: 500,
title: 'Array Grid',
renderTo: 'grid-example',
stripeRows: true
});
});

ASP.NET webservice:


using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
using System.Web.Script.Services;
using System.Web.Script.Serialization;


[WebService(Namespace = "http://tempuri.org")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
public WebService () {
}

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true, XmlSerializeString = false)]
public string GetData() {
String Query = "select * from SalesLT.Address";
DataSet myDataSet = new DataSet();
string connectionString = ConfigurationManager.ConnectionStrings["EmployeesDatabase"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(Query, connection);
mySqlDataAdapter.Fill(myDataSet);
}
return GetJSONString(myDataSet.Tables[0]);
}

public static string GetJSONString(DataTable Dt)
{
string[] StrDc = new string[Dt.Columns.Count];
string HeadStr = string.Empty;
for (int i = 0; i < Dt.Columns.Count; i++)
{
StrDc[i] = Dt.Columns[i].Caption;
HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "" + "\",";
}
HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);
StringBuilder Sb = new StringBuilder();
Sb.Append("{\"" + Dt.TableName + "\" : [");
for (int i = 0; i < Dt.Rows.Count; i++)
{
string TempStr = HeadStr;
Sb.Append("{");
for (int j = 0; j < Dt.Columns.Count; j++)
{
TempStr = TempStr.Replace(Dt.Columns[j] + j.ToString() + "", Dt.Rows[i][j].ToString());
}
Sb.Append(TempStr + "},");
}
Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
Sb.Append("]}");
return Sb.ToString();
}
}


Firebug Console Error (with data):


'Unable to parse the JSON returned by the server: You're trying to decode an invalid JSON String:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://campbellalliance.com/parth">
{"Table" : [

{"AddressID" : "9","AddressLine1" : "8713 Yosemite Ct.","AddressLine2" : "","City" : "Bothell","StateProvince" : "Washington","CountryRegion" : "United States","PostalCode" : "98011","rowguid" : "268af621-76d7-4c78-9441-144fd139821a","ModifiedDate" : "7/1/2002 12:00:00 AM"},

{"AddressID" : "11","AddressLine1" : "1318 Lasalle Street","AddressLine2" : "","City" : "Bothell","StateProvince" : "Washington","CountryRegion" : "United States","PostalCode" : "98011","rowguid" : "981b3303-aca2-49c7-9a96-fb670785b269","ModifiedDate" : "4/1/2003 12:00:00 AM"},

{"AddressID" : "25","AddressLine1" : "9178 Jumping St.","AddressLine2" : "","City" : "Dallas","StateProvince" : "Texas","CountryRegion" : "United States","PostalCode" : "75201","rowguid" : "c8df3bd9-48f0-4654-a8dd-14a67a84d3c6","ModifiedDate" : "9/1/2002 12:00:00 AM"},

{"AddressID" : "28","AddressLine1" : "9228 Via Del Sol","AddressLine2" : "","City" : "Phoenix","StateProvince" : "Arizona","CountryRegion" : "United States","PostalCode" : "85004","rowguid" : "12ae5ee1-fc3e-468b-9b92-3b970b169774","ModifiedDate" : "9/1/2001 12:00:00 AM"}

]}

</string>'
when calling method:[nsIDOMEventListener::handleEvent]


Thanks,
Parth

mitchellsimoens
28 Feb 2012, 5:33 PM
You do realize that your JSON has XML surrounding it right?

ppatel2
1 Mar 2012, 7:23 AM
How can I get the data out of that string and bind it to the grid ? Can you please tell me what am I doing wrong or give me a small example to solve this issue ?

Thanks,
Parth

mitchellsimoens
1 Mar 2012, 7:26 AM
Are you returning only JSON now?

ppatel2
1 Mar 2012, 7:46 AM
Yes, right now I am trying to return the json string. I can use xml too. What is the best way to return the data from the ASP.NET webservices (Json string or Xml) ?

mitchellsimoens
1 Mar 2012, 7:48 AM
The favored response is JSON.

ppatel2
1 Mar 2012, 8:41 AM
I changed my code and now there is no error. The Json data is received but the grid is not populated. Can you please tell me what am I missing here ?

Json Data:



{"d":"[{\"AddressID\" : \"9\",\"AddressLine1\" : \"8713 Yosemite Ct.\",\"AddressLine2\" : \"\",\"City\" : \"Bothell\",\"StateProvince\" : \"Washington\",\"CountryRegion\" : \"United States\",\"PostalCode\" : \"98011\",\"rowguid\" : \"268af621-76d7-4c78-9441-144fd139821a\",\"ModifiedDate\" : \"7/1/2002 12:00:00 AM\"}]}"}


ExtJS code


Ext.onReady(function() {


Ext.define('Address', {
extend: 'Ext.data.Model',
fields: ['AddressID', 'AddressLine1', 'AddressLine2', 'City', 'StateProvince', 'CountryRegion', 'PostalCode', 'rowguid', 'ModifiedDate']
});

// create the data store
var store = new Ext.data.Store({
model: 'Address',
autoLoad: true,
proxy: {
type: 'ajax',
url: 'WebService.asmx/HelloWorld',
headers: { 'Content-type': 'application/json; charset=utf-8' },
reader: {
type: 'json',
root: 'd'
}
}
});

// create the Grid
var grid = new Ext.grid.GridPanel({
store: store,
columns: [
{
header: 'AddressID',
dataIndex: 'AddressID'
},
{
header: 'AddressLine1',
dataIndex: 'AddressLine1'
},
{
header: 'AddressLine2',
dataIndex: 'AddressLine2'
},
{
header: 'City',
dataIndex: 'City'
},
{
header: 'StateProvince',
dataIndex: 'StateProvince'
},
{
header: 'CountryRegion',
dataIndex: 'CountryRegion'
},
{
header: 'PostalCode',
dataIndex: 'PostalCode'
},
{
header: 'rowguid',
dataIndex: 'rowguid'
},
{
header: 'ModifiedDate',
dataIndex: 'ModifiedDate'
}
],
height: 500,
width: 902,
title: 'Array Grid',
renderTo: 'grid-example',
stripeRows: true
});
});


ASP.NET Webservice code (returning a string):


[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true, XmlSerializeString = false)]
public string HelloWorld() {
String Query = "select * from SalesLT.Address";
DataSet myDataSet = new DataSet();
string connString = ConfigurationManager.ConnectionStrings["EmployeesDatabase"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connString))
{
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(Query, connection);
mySqlDataAdapter.Fill(myDataSet);
}
return "[{\"AddressID\" : \"9\",\"AddressLine1\" : \"8713 Yosemite Ct.\",\"AddressLine2\" : \"\",\"City\" : \"Bothell\",\"StateProvince\" : \"Washington\",\"CountryRegion\" : \"United States\",\"PostalCode\" : \"98011\",\"rowguid\" : \"268af621-76d7-4c78-9441-144fd139821a\",\"ModifiedDate\" : \"7/1/2002 12:00:00 AM\"}]}";
}

ppatel2
1 Mar 2012, 10:37 AM
I tried to check the record count using the code below which returns 0. But the firebug console shows the json string with 1 record.



var recs = store.getRange();
alert(recs.length);


Firebug Console data:



{"d":"[{\"AddressID\" : \"9\",\"AddressLine1\" : \"8713 Yosemite Ct.\",\"AddressLine2\" : \"\",\"City\" : \"Bothell\",\"StateProvince\" : \"Washington\",\"CountryRegion\" : \"United States\",\"PostalCode\" : \"98011\",\"rowguid\" : \"268af621-76d7-4c78-9441-144fd139821a\",\"ModifiedDate\" : \"7/1/2002 12:00:00 AM\"}]}"}

skirtle
1 Mar 2012, 11:11 AM
Your JSON is still a mess. What you have is an object with a property d that has a massive string value. What you want is for that value to be an array. You've got an escaping problem somewhere on your server.

ppatel2
1 Mar 2012, 12:35 PM
Ok, finally I was able to figure out the issue. I was returning the data as a string created manually from the web services in the json string format. Then, I tried to create the object and returned that object and it was automatically converted to the Json format. But still I was not able to populate the grid. Then I changed my ExtJS code and added "fields" attribute in the model and it worked. Here is the working code.

ASP.NET web service code:


using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Collections;


[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class WebService2 : System.Web.Services.WebService {
public WebService2 () { }


[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json, UseHttpGet=true,XmlSerializeString=false)]
public List<Address> HelloWorld() {
List<Address> list = buildList();
return list;
}


public List<Address> buildList()
{
List<Address> list = new List<Address>();
Address add = new Address(9,"8713 Yosemite Ct.","","Bothell","Washington","United States", "98011", "268af621-76d7-4c78-9441-144fd139821a", "1/7/2002");
list.Add(add);
add = new Address(10, "8713 Yosemite Ct.", "", "Bothell", "Washington", "United States", "98011", "268af621-76d7-4c78-9441-144fd139821a", "1/7/2002");
list.Add(add);
add = new Address(11, "8713 Yosemite Ct.", "", "Bothell", "Washington", "United States", "98011", "268af621-76d7-4c78-9441-144fd139821a", "1/7/2002");
list.Add(add);
return list;
}
}


public class Address
{
private int addressID;
private string addressLine1;
private string addressLine2;
private string city;
private string stateProvince;
private string countryRegion;
private string postalCode;
private string guid;
private string modifiedDate;


public Address() { }


public Address(int _addressID, string _addressLine1, string _addressLine2, string _city, string _stateProvince, string _countryRegion,
string _postalCode, string _rowguid, string _modifiedDate)
{
addressID = _addressID;
addressLine1 = _addressLine1;
addressLine2 = _addressLine2;
city = _city;
stateProvince = _stateProvince;
countryRegion = _countryRegion;
postalCode = _postalCode;
guid = _rowguid;
modifiedDate = _modifiedDate;
}


public int AddressID
{
get
{ return addressID;}
set
{ addressID =value;}
}


public string AddressLine1
{
get
{return addressLine1;}
set
{addressLine1 = value;}
}


public string AddressLine2
{
get
{return addressLine2;}
set
{addressLine2 = value;}
}


public string City
{
get
{return city;}
set
{city = value;}
}


public string StateProvince
{
get
{return stateProvince;}
set
{stateProvince = value;}
}


public string CountryRegion
{
get
{return countryRegion;}
set
{countryRegion = value;}
}


public string PostalCode
{
get
{return postalCode;}
set
{postalCode = value;}
}


public string rowGuid
{
get
{return guid;}
set
{guid = value;}
}


public string ModifiedDate
{
get
{return modifiedDate;}
set
{modifiedDate = value;}
}
}





ExtJS code:


Ext.onReady(function() {


Ext.define('Address', {
extend: 'Ext.data.Model',
fields: ['AddressID','AddressLine1','AddressLine2','City','StateProvince','CountryRegion','PostalCode','rowguid','ModifiedDate']
});


var store = new Ext.data.JsonStore({
model: 'Address',
autoLoad: true,
proxy: {
type: 'ajax',
url: 'WebService2.asmx/HelloWorld',
headers: { 'Content-type': 'application/json; charset=utf-8' },
reader: {
type: 'json',
root: 'd'
}
}
});


var grid = new Ext.grid.GridPanel({
store: store,
columns: [
{ header: 'AddressID', dataIndex: 'AddressID'},
{ header: 'AddressLine1', dataIndex: 'AddressLine1'},
{ header: 'AddressLine2', dataIndex: 'AddressLine2'},
{ header: 'City', dataIndex: 'City'},
{ header: 'StateProvince', dataIndex: 'StateProvince'},
{ header: 'CountryRegion', dataIndex: 'CountryRegion'},
{ header: 'PostalCode', dataIndex: 'PostalCode'},
{ header: 'rowguid', dataIndex: 'rowguid'},
{ header: 'ModifiedDate', dataIndex: 'ModifiedDate'}],
height: 500,
width: 902,
title: 'Array Grid',
renderTo: 'grid-example',
stripeRows: true
});
});


ASPX page:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExtJSGrid.aspx.cs" Inherits="ExtJSGrid" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Organization Chart</title>
<link href="extjs/resources/css/ext-all.css" rel="stylesheet" type="text/css" />
<script src="extjs/ext-all-debug.js" type="text/javascript"></script>
<script src="scripts/JScript1.js" type="text/javascript"></script>
</head>
<body>
<div id="grid-example" style="width:500px;height:600px">
</div>
</body>
</html>


Hopefully, this helps someone to get started.