Pages

Showing posts with label serialization. Show all posts
Showing posts with label serialization. Show all posts

Tuesday, March 12, 2013

Endpoint on ASP.NET page returning JSON from DataTable

I was trying to get an web service, on my aspx page which returned data would be JSON.

The structure of JSON returned usually is something similar to this:

{ "d" :  [ {...}, {...}, {...} ] }

To achieve this, I purpose this approach:


First - Create an WebMethod on your page, at server side, like this:

        [System.Web.Services.WebMethod]
        public static string GetData()
        {
            DataTable dt = GetDataTable();
            
            return BuildJSONFromDT(dt);
        }



Second - Create the method "BuildJSONFromDT"

 

        private static string BuildJSONFromDT(DataTable dt)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            List<object> resultMain = new List<object>();

            foreach (DataRow row in dt.Rows)
            {
                Dictionary<string, object> result = new Dictionary<string, object>();
                foreach (DataColumn column in dt.Columns)
                {
                    result.Add(column.ColumnName, "" + row[column.ColumnName]);
                }

                resultMain.Add(result);
            }

            return serializer.Serialize(resultMain);
        }



Third - At client side, do an ajax call with jquery like this:

$.ajax({
        type: "POST",
        async: true,
        contentType: "application/json; charset=utf-8",
        data: "{}",
        url: "page.aspx/GetData",
        dataType: "json",
        success: function (result) {
            var myData = eval(result.d);
            // Work on myData object (JSON)
        },
        error: function (data, textStatus, jqXHR) {
            alert("Error: " + textStatus);
        }
    });



At this point, you should have an valid JSON at client side reflecting your DataTable retrieved on server side.

Hope this helps someone.

Cheers!


Reference:
http://geekswithblogs.net/aghausman/archive/2009/05/16/datatable-to-json.aspx

Monday, August 27, 2012

Request JSON using WCF DS 5.0

So, I was start using WCF OData Services 5.0.1.0 and when I made an ajax call requesting the response in JSON I get the 415 error: "Unsupported media type requested".

Detail: "A supported MIME type could not be found that matches the acceptable MIME types for the request. The supported type(s) 'application/atom+xml;type=feed, application/atom+xml, application/json;odata=verbose' do not match any of the acceptable MIME types 'application/json'".

This happens because the serialization json light format will be part of the OData v3 protocol: "The new serialization format will be part of the OData v3 protocol, and we believe that the much-improved JSON format should be the default response when requesting application/json." (http://blogs.msdn.com/b/astoriateam/archive/2012/04/11/what-happened-to-application-json-in-wcf-ds-5-0.aspx)

In conclusion, you have the next code on your WCF OData Service:
public class api : DataService <DataModel>
{
 public static void InitializeService(DataServiceConfiguration config)
 {
  config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
  config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
 }
}



And to call the service using javascript/jquery you can use the next code for that:
$.ajax({
  type: "GET",
  url: "api.svc/Entity()?$top=10",
  dataType: "json",
  beforeSend: function (xhr) {
    xhr.setRequestHeader("Accept", "application/json;odata=verbose");
  },
  success: function (data) {
    //success func
  },
  error: function (error) {
    //error func
  }
});


References:
http://blogs.msdn.com/b/astoriateam/archive/2012/04/11/what-happened-to-application-json-in-wcf-ds-5-0.aspx
http://blogs.msdn.com/b/astoriateam/archive/2012/04/09/wcf-data-services-5-0-rtm-release.aspx
http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataservices/thread/ae80bb85-ad26-48c4-a399-4d76db5c346b

Tuesday, March 15, 2011

C# - XML Serialization of Class

Always useful!!! For whatever reason, it's always good to know how to serialize your class into a file, or any other kind of Stream. This example has one simple class with two properties, but it could be a global variable either, and the XmlSerializer usage.





















The result file of this example, looks like this:







Besides this, the serialization is not complete with the deserialization :) That's pretty simple to!








References:
http://support.microsoft.com/kb/815813/en-us