badrhino
asked on
Return Json from VB.NET
I'm trying to return Json to the client so I can use it in AmCharts. Currently I make a typical $.AJAx call which fires my webmethod, the database is queried and I return the data. However, no matter what I try, the data does not come back in a form that AMCharts can use. I've tried putting the data into a dictionary, serializing the data explicitly, using <ScriptService>_ and even trying to format the JSON as a string. The string method came the closest, but of course it was escaped with "\". The data always gets back to the client, but usually as an object or string that isn't formated correctly.
Right now I'm not to concerned about anything other than returning a string/object/something and having it being able to be consumed by AMCharts.
The data for AMCharts need to look like the following:
var chartData = [{
country: "USA",
visits: 4025,
color: "#FF0F00"
}, {
country: "China",
visits: 1882,
color: "#FF6600"
}, {
country: "Japan",
visits: 1809,
color: "#FF9E01"
}
So I want to return a string/object/something that I can do this with:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "SomePage.aspx/Get_JSON",
data: '{}',
dataType: "json",
success:function (data) {
var chartData= data;
makeChart(chartData);
} ,
error: function (result) {
alert("Error");
}
});
function makeChart(chartData2) {
var chartData=chartData2
//Code for amcharts follows.....
}
Right now I'm not to concerned about anything other than returning a string/object/something and having it being able to be consumed by AMCharts.
The data for AMCharts need to look like the following:
var chartData = [{
country: "USA",
visits: 4025,
color: "#FF0F00"
}, {
country: "China",
visits: 1882,
color: "#FF6600"
}, {
country: "Japan",
visits: 1809,
color: "#FF9E01"
}
So I want to return a string/object/something that I can do this with:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "SomePage.aspx/Get_JSON",
data: '{}',
dataType: "json",
success:function (data) {
var chartData= data;
makeChart(chartData);
} ,
error: function (result) {
alert("Error");
}
});
function makeChart(chartData2) {
var chartData=chartData2
//Code for amcharts follows.....
}
ASKER
leakim971-
Page is still on my computer, not on a server yet.
I just got it to work by commenting the <scriptMethod> out. Below is the code that I used. I'm new to vb.net and JSON, is there a better way?
This is the code that was escaped:
<WebMethod()> _
'<ScriptMethod(ResponseFor mat:=Respo nseFormat. Json)> _ 'Commented this line and
' it works.
Public Shared Function get_Json()
Dim json as string
json = "[{county:""USA"",visits:" "4025"",co lor:""#ff0 f00""},{co unty:""Chi na"",visit s:""1882"" ,color:""# ff6600""}, {county:"" Japan"",vi sits:""250 0"",color: ""#ff9e01" "}"
Return json
I understand that you aren't supposed to do it this way... Do you have any suggestions?
The data that returned after I commented the <scriptMethod....>_ is:
[{county:"USA",visits:"402 5",color:" #ff0f00"}, {county:"C hina",visi ts:"1882", color:"#ff 6600"},{co unty:"Japa n",visits: "2500",col or:"#ff9e0 1"}
Page is still on my computer, not on a server yet.
I just got it to work by commenting the <scriptMethod> out. Below is the code that I used. I'm new to vb.net and JSON, is there a better way?
This is the code that was escaped:
<WebMethod()> _
'<ScriptMethod(ResponseFor
' it works.
Public Shared Function get_Json()
Dim json as string
json = "[{county:""USA"",visits:"
Return json
I understand that you aren't supposed to do it this way... Do you have any suggestions?
The data that returned after I commented the <scriptMethod....>_ is:
[{county:"USA",visits:"402
using PageMethods simplify the way you use Ajax with .Net application, a random link :
http://www.dotnetfunda.com/articles/article454-using-pagemethods-and-json-in-aspnet-ajax.aspx
http://www.dotnetfunda.com/articles/article454-using-pagemethods-and-json-in-aspnet-ajax.aspx
ASKER
Scratch that.....This method isn't working....still being escaped:
If I use Alert(data); a message box comes up and says [object Object].
If I hover over the data variable (I'm in VS 2012), it shows the object being escaped .
If I click on the variable a box comes up showing it not escaped. Either way, my chart isn't working.....
If I use Alert(data); a message box comes up and says [object Object].
If I hover over the data variable (I'm in VS 2012), it shows the object being escaped .
If I click on the variable a box comes up showing it not escaped. Either way, my chart isn't working.....
ASKER
I'm looking at your link now...
I would suggest you to take a look at http://json.codeplex.com/.
I'm sure you will not be disappointed!
Regards.
I'm sure you will not be disappointed!
Regards.
ASKER
I've converted the above link into VB.Net. This is what I've got. However, I'm getting an error with the DataContractJsonSerializer class. I've imported System.Runtime.Seriializat ion, but still no luck.
Public Class SomePage
Inherits System.Web.UI.Page
<WebMethod()> _
Public Shared Function GetData(f As String, s As String) As String
Dim p As New Person()
p.Forename = "f"
p.Surname = "s"
' throw new Exception("Custom Error :) ");
Return SerializeObjectIntoJson(p)
End Function
Public Class Person
Private m_forename As String = String.Empty
Private m_surname As String = String.Empty
Public Property Forename() As String
Get
Return m_forename
End Get
Set(value As String)
m_forename = value
End Set
End Property
Public Property Surname() As String
Get
Return m_surname
End Get
Set(value As String)
m_surname = value
End Set
End Property
End Class
Shared Function SerializeObjectIntoJson(p As Person) As String
Dim serializer As New DataContractJsonSerializer (p.[GetTyp e]())
Using ms As New MemoryStream()
serializer.WriteObject(ms, p)
ms.Flush()
Dim bytes As Byte() = ms.GetBuffer()
Dim jsonString As String = Encoding.UTF8.GetString(by tes, 0, bytes.Length).Trim(Control Chars.Null Char)
Return jsonString
End Using
End Function
End Class
Public Class SomePage
Inherits System.Web.UI.Page
<WebMethod()> _
Public Shared Function GetData(f As String, s As String) As String
Dim p As New Person()
p.Forename = "f"
p.Surname = "s"
' throw new Exception("Custom Error :) ");
Return SerializeObjectIntoJson(p)
End Function
Public Class Person
Private m_forename As String = String.Empty
Private m_surname As String = String.Empty
Public Property Forename() As String
Get
Return m_forename
End Get
Set(value As String)
m_forename = value
End Set
End Property
Public Property Surname() As String
Get
Return m_surname
End Get
Set(value As String)
m_surname = value
End Set
End Property
End Class
Shared Function SerializeObjectIntoJson(p As Person) As String
Dim serializer As New DataContractJsonSerializer
Using ms As New MemoryStream()
serializer.WriteObject(ms,
ms.Flush()
Dim bytes As Byte() = ms.GetBuffer()
Dim jsonString As String = Encoding.UTF8.GetString(by
Return jsonString
End Using
End Function
End Class
What is the error you get?
ASKER
Type DataContractJsonSerializer is not defined.
Did you implement #leakim971's solution?
ASKER
If I bypass the serializeobjectIntoJason function and use this:
Dim json As New JavaScriptSerializer
Return json.Serialize(p)
I get the following output:
"{\"Forename\":\"FirstName \",\"Surna me\":\"Las tName\"}"
Full code:
Public Shared Function GetData() As String
Dim p As New Person()
p.Forename = "FirstName"
p.Surname = "LastName"
' throw new Exception("Custom Error :) ");
' Return SerializeObjectIntoJson(p)
Dim json As New JavaScriptSerializer
Return json.Serialize(p)
End Function
Dim json As New JavaScriptSerializer
Return json.Serialize(p)
I get the following output:
"{\"Forename\":\"FirstName
Full code:
Public Shared Function GetData() As String
Dim p As New Person()
p.Forename = "FirstName"
p.Surname = "LastName"
' throw new Exception("Custom Error :) ");
' Return SerializeObjectIntoJson(p)
Dim json As New JavaScriptSerializer
Return json.Serialize(p)
End Function
ASKER
jonnidip, I'm trying to, but it isn't working.
ASKER
jonnidip:
I just tried json.net. The results I got were escaped also.....
"{\"Forename\":\"FirstName \",\"Surna me\":\"Las tName\"}"
I just tried json.net. The results I got were escaped also.....
"{\"Forename\":\"FirstName
I get the following output:So you can use :
"{\"Forename\":\"FirstName\",\"Surna me\":\"Las tName\"}"
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "SomePage.aspx/Get_JSON",
data: '{}',
dataType: "json",
success:function (data) {
//var person = jQuery.parseJSON("{\"Forename\":\"FirstName\",\"Surname\":\"LastName\"}")
var person = jQuery.parseJSON(data);
alert(person.Forename);
alert(person.Surname);
makeChart(person);
} ,
error: function (result) {
alert("Error");
}
});
ASKER
leakim971.
That worked. However my chart doesn't seem to recognize the data. Any suggestions? I'm going to go over my code and make sure I don't have any mistakes....
That worked. However my chart doesn't seem to recognize the data. Any suggestions? I'm going to go over my code and make sure I don't have any mistakes....
I don't see any relation between :
Once you show me some "real" data, I can help
[{
country: "USA",
visits: 4025,
color: "#FF0F00"
}, {
country: "China",
visits: 1882,
color: "#FF6600"
}, {
country: "Japan",
visits: 1809,
color: "#FF9E01"
}
]
and :{
"Forename":"FirstName",
"Surname":"LastName"
}
Once you show me some "real" data, I can help
ASKER
I think the data needs to stay serialized for the chart to recognize. How do we do this and not have the \?
ASKER
leakin, sorry for the disconnect. I modified the class. Here is the code:
Code Behind:
<WebMethod()> _
Public Shared Function getData()
Dim p As New Person()
p.Country = "USA"
p.Visits = "4025"
p.color = "#FF0F00"
' throw new Exception("Custom Error :) ");
Dim json As New JavaScriptSerializer
Return json.Serialize(p)
End Function
Public Class Person
Private m_country As String = String.Empty
Private m_visits As String = String.Empty
Private m_color As String = String.Empty
Public Property Country() As String
Get
Return m_country
End Get
Set(value As String)
m_country = value
End Set
End Property
Public Property Visits() As String
Get
Return m_visits
End Get
Set(value As String)
m_visits = value
End Set
End Property
Public Property color() As String
Get
Return m_color
End Get
Set(value As String)
m_color = value
End Set
End Property
End Class
Client Side:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "somepage.aspx/getData",
data: '{}',
dataType: "json",
success:function (data) {
var chartData = data.d;
var test = $.parseJSON(chartData);
alert(test.color);
makeChart(test);
} ,
error: function (result) {
alert("Error");
}
});
function makeChart(chartData) {
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.dataProvider = chartData;
chart.categoryField = "country";
// the following two lines makes chart 3D
chart.depth3D = 20;
chart.angle = 30;
// AXES
// category
var categoryAxis = chart.categoryAxis;
categoryAxis.labelRotation = 90;
categoryAxis.dashLength = 0;
categoryAxis.gridPosition = "start";
// value
var valueAxis = new AmCharts.ValueAxis();
valueAxis.title = "Visitors";
valueAxis.dashLength = 5;
chart.addValueAxis(valueAx is);
// GRAPH
var graph = new AmCharts.AmGraph();
graph.valueField = "visits";
graph.colorField = "color";
graph.balloonText = "[[category]]: [[value]]";
graph.type = "column";
graph.lineAlpha = 0;
graph.fillAlphas = 1;
chart.addGraph(graph);
// WRITE
chart.write("chartdiv");
}; //function make chart
}); //Document Ready
Code Behind:
<WebMethod()> _
Public Shared Function getData()
Dim p As New Person()
p.Country = "USA"
p.Visits = "4025"
p.color = "#FF0F00"
' throw new Exception("Custom Error :) ");
Dim json As New JavaScriptSerializer
Return json.Serialize(p)
End Function
Public Class Person
Private m_country As String = String.Empty
Private m_visits As String = String.Empty
Private m_color As String = String.Empty
Public Property Country() As String
Get
Return m_country
End Get
Set(value As String)
m_country = value
End Set
End Property
Public Property Visits() As String
Get
Return m_visits
End Get
Set(value As String)
m_visits = value
End Set
End Property
Public Property color() As String
Get
Return m_color
End Get
Set(value As String)
m_color = value
End Set
End Property
End Class
Client Side:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "somepage.aspx/getData",
data: '{}',
dataType: "json",
success:function (data) {
var chartData = data.d;
var test = $.parseJSON(chartData);
alert(test.color);
makeChart(test);
} ,
error: function (result) {
alert("Error");
}
});
function makeChart(chartData) {
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.dataProvider = chartData;
chart.categoryField = "country";
// the following two lines makes chart 3D
chart.depth3D = 20;
chart.angle = 30;
// AXES
// category
var categoryAxis = chart.categoryAxis;
categoryAxis.labelRotation
categoryAxis.dashLength = 0;
categoryAxis.gridPosition = "start";
// value
var valueAxis = new AmCharts.ValueAxis();
valueAxis.title = "Visitors";
valueAxis.dashLength = 5;
chart.addValueAxis(valueAx
// GRAPH
var graph = new AmCharts.AmGraph();
graph.valueField = "visits";
graph.colorField = "color";
graph.balloonText = "[[category]]: [[value]]";
graph.type = "column";
graph.lineAlpha = 0;
graph.fillAlphas = 1;
chart.addGraph(graph);
// WRITE
chart.write("chartdiv");
}; //function make chart
}); //Document Ready
How do we do this and not have the \?
forget this, it normal to see that << \" >> inside a JSON string
what is th data you want really to send?
It's really surname and forename? where's the color?
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "SomePage.aspx/Get_JSON",
data: '{}',
dataType: "json",
success:function (data) {
var person = jQuery.parseJSON(data);
person.color = "#FF0F00";
var arr = [];
arr.push(person)
makeChart(arr);
} ,
error: function (result) {
alert("Error");
}
});
Sorry I did not saw your last post before now
could you post what you get exactly in the alert :
could you post what you get exactly in the alert :
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "somepage.aspx/getData",
data: '{}',
dataType: "json",
success:function (data) {
var chartData = data.d;
var test = $.parseJSON(chartData);
alert(JSON.stringify(test));
// makeChart(test);
} ,
error: function (result) {
alert("Error");
}
});
ASKER
{"Country":"USA","Visits": "4025","co lor":"#FF0 FF00"}
Looking at this, country and visits need to be lowercase. I will fix that and let you know.
Looking at this, country and visits need to be lowercase. I will fix that and let you know.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Didn't make a difference....
ASKER
hold on. Let me try your response changing to lowercase didn't make a difference....
ASKER
That Worked!!!!
I'm going to close the ticket and fiddle around with bringing more than one country across. If I have problems with this I will create a new ticket.
Thanks for your help....!
I'm going to close the ticket and fiddle around with bringing more than one country across. If I have problems with this I will create a new ticket.
Thanks for your help....!
ASKER
Prompt and very easy to understand. Thanks!
could you provide a link to see your page?
Could you post the best object your get from the server side, for example the one escaped?
Open in new window