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.....
}
LVL 1
badrhinoAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
leakim971Connect With a Mentor PluritechnicianCommented:
Looking at this, country and visits need to be lowercase
OK and the whole object inside an array :

$.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "somepage.aspx/getData",
                data: '{}',
                dataType: "json",
                success:function (data) {
                    var chartData = data.d; // good !!!
                    var test = [];
                    test.push( $.parseJSON(chartData)  );
                    makeChart(test);
                }  ,
                error: function (result) {
                    alert("Error");
                }
            });

Open in new window

0
 
leakim971PluritechnicianCommented:
where is your server side code?
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?

success:function (data) {
alert(data); // post what you get here
                    }  ,

Open in new window

0
 
badrhinoAuthor Commented:
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(ResponseFormat:=ResponseFormat.Json)> _ 'Commented  this line and
' it works.
    Public Shared Function get_Json()
Dim json as string

        json = "[{county:""USA"",visits:""4025"",color:""#ff0f00""},{county:""China"",visits:""1882"",color:""#ff6600""},{county:""Japan"",visits:""2500"",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:"4025",color:"#ff0f00"},{county:"China",visits:"1882",color:"#ff6600"},{county:"Japan",visits:"2500",color:"#ff9e01"}
0
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
leakim971PluritechnicianCommented:
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
0
 
badrhinoAuthor Commented:
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.....
0
 
badrhinoAuthor Commented:
I'm looking at your link now...
0
 
jonnidipCommented:
I would suggest you to take a look at http://json.codeplex.com/.
I'm sure you will not be disappointed!

Regards.
0
 
badrhinoAuthor Commented:
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.Seriialization, 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.[GetType]())
        Using ms As New MemoryStream()
            serializer.WriteObject(ms, p)
            ms.Flush()

            Dim bytes As Byte() = ms.GetBuffer()
            Dim jsonString As String = Encoding.UTF8.GetString(bytes, 0, bytes.Length).Trim(ControlChars.NullChar)
            Return jsonString
        End Using
    End Function
End Class
0
 
jonnidipCommented:
What is the error you get?
0
 
badrhinoAuthor Commented:
Type DataContractJsonSerializer is not defined.
0
 
jonnidipCommented:
Did you implement #leakim971's solution?
0
 
badrhinoAuthor Commented:
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\",\"Surname\":\"LastName\"}"

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
0
 
badrhinoAuthor Commented:
jonnidip, I'm trying to, but it isn't working.
0
 
badrhinoAuthor Commented:
jonnidip:
I just tried json.net.  The results I got were escaped also.....

"{\"Forename\":\"FirstName\",\"Surname\":\"LastName\"}"
0
 
leakim971PluritechnicianCommented:
I get the following output:
 
"{\"Forename\":\"FirstName\",\"Surname\":\"LastName\"}"
So you can use :
$.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");
                }
            });

Open in new window

0
 
badrhinoAuthor Commented:
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....
0
 
leakim971PluritechnicianCommented:
I don't see any relation between :
[{
                country: "USA",
                visits: 4025,
                color: "#FF0F00"
            }, {
                country: "China",
                visits: 1882,
                color: "#FF6600"
            }, {
                country: "Japan",
                visits: 1809,
                color: "#FF9E01"
            }
]

Open in new window

and :
{
      "Forename":"FirstName",
      "Surname":"LastName"
}

Open in new window


Once you show me some "real" data, I can help
0
 
badrhinoAuthor Commented:
I think the data needs to stay serialized for the chart to recognize.  How do we do this and not have the \?
0
 
badrhinoAuthor Commented:
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(valueAxis);

                // 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
0
 
leakim971PluritechnicianCommented:
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");
                }
            });

Open in new window

0
 
leakim971PluritechnicianCommented:
Sorry I did not saw your last post before now
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");
                }
            });

Open in new window

0
 
badrhinoAuthor Commented:
{"Country":"USA","Visits":"4025","color":"#FF0FF00"}

Looking at this, country and visits need to be lowercase.  I will fix that and let you know.
0
 
badrhinoAuthor Commented:
Didn't make a difference....
0
 
badrhinoAuthor Commented:
hold on.  Let me try your response changing to lowercase didn't make a difference....
0
 
badrhinoAuthor Commented:
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....!
0
 
badrhinoAuthor Commented:
Prompt and very easy to understand.  Thanks!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.