Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Return Json from VB.NET

Posted on 2013-02-01
26
Medium Priority
?
1,367 Views
Last Modified: 2013-02-01
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.....
}
0
Comment
Question by:badrhino
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 16
  • 7
  • 3
26 Comments
 
LVL 82

Expert Comment

by:leakim971
ID: 38843735
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
 
LVL 1

Author Comment

by:badrhino
ID: 38843795
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
 
LVL 82

Expert Comment

by:leakim971
ID: 38843816
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
The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

 
LVL 1

Author Comment

by:badrhino
ID: 38843833
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
 
LVL 1

Author Comment

by:badrhino
ID: 38843870
I'm looking at your link now...
0
 
LVL 13

Expert Comment

by:jonnidip
ID: 38843903
I would suggest you to take a look at http://json.codeplex.com/.
I'm sure you will not be disappointed!

Regards.
0
 
LVL 1

Author Comment

by:badrhino
ID: 38843942
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
 
LVL 13

Expert Comment

by:jonnidip
ID: 38843947
What is the error you get?
0
 
LVL 1

Author Comment

by:badrhino
ID: 38844055
Type DataContractJsonSerializer is not defined.
0
 
LVL 13

Expert Comment

by:jonnidip
ID: 38844077
Did you implement #leakim971's solution?
0
 
LVL 1

Author Comment

by:badrhino
ID: 38844124
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
 
LVL 1

Author Comment

by:badrhino
ID: 38844129
jonnidip, I'm trying to, but it isn't working.
0
 
LVL 1

Author Comment

by:badrhino
ID: 38844205
jonnidip:
I just tried json.net.  The results I got were escaped also.....

"{\"Forename\":\"FirstName\",\"Surname\":\"LastName\"}"
0
 
LVL 82

Expert Comment

by:leakim971
ID: 38844229
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
 
LVL 1

Author Comment

by:badrhino
ID: 38844282
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
 
LVL 82

Expert Comment

by:leakim971
ID: 38844295
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
 
LVL 1

Author Comment

by:badrhino
ID: 38844299
I think the data needs to stay serialized for the chart to recognize.  How do we do this and not have the \?
0
 
LVL 1

Author Comment

by:badrhino
ID: 38844310
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
 
LVL 82

Expert Comment

by:leakim971
ID: 38844326
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
 
LVL 82

Expert Comment

by:leakim971
ID: 38844328
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
 
LVL 1

Author Comment

by:badrhino
ID: 38844355
{"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
 
LVL 82

Accepted Solution

by:
leakim971 earned 2000 total points
ID: 38844368
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
 
LVL 1

Author Comment

by:badrhino
ID: 38844370
Didn't make a difference....
0
 
LVL 1

Author Comment

by:badrhino
ID: 38844378
hold on.  Let me try your response changing to lowercase didn't make a difference....
0
 
LVL 1

Author Comment

by:badrhino
ID: 38844428
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
 
LVL 1

Author Closing Comment

by:badrhino
ID: 38844433
Prompt and very easy to understand.  Thanks!
0

Featured Post

New benefit for Premium Members - Upgrade now!

Ready to get started with anonymous questions today? It's easy! Learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

670 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question