Ahmad Masykur

Share your knowledge although one function!

About the author

Ahmad Masykur is a Software Architecture Engineer at PT. Freeport Indonesia Jakarta Indonesia.
In this blog, I share things of interest to me. Most topics are likely to be related to software development, but don't hold me to it.

Certificates



Awards


Powered by

Widget Prayer Time not found.

There is an error in XML document (4, 16278).X

Page List

Validators


Ahmad Masykur

JSON vs XML

JSON (JavaScript Object Notation) merupakan format pertukaran data berdasarkan notasi JavaScript. Dari beberapa sumber mengatakan bahwa JSON lebih baik dari XML sebagai format pertukaran data. Benarkah demikian? Saya coba untuk membuat test sedarhana membandingkan kedua format data tersebut pada ASP.NET WebService.

Saya menggunakan dua parameter pembanding yaitu besar stream yang ditransmisikan dan response time. Untuk menganalisis kinerja keduanya saya gunakan tool buatan Nikhil Kotari yaitu Web Development Helper yang dapat di download dari situs pribadinya di Nikhil Kothari's Projects - Web Development Helper

Pertama saya buat sebuat object Employee dengan data EmpId, Name, Sex dan Title. object ini yang akan diserialisasi ke JSON dan XML sebagai return value WebService.

namespace JSONSample
{
    public class Employee
    {
        public string EmpId { get; set; }
        public string Name { get; set; }
        public string Title { get; set; }
        public char Sex { get; set; }
    }
}

Selanjutnya buat web service dengan dua method yang mengembalikan Employee dalam format JSON dan XML. Jangan lupa untuk menambahkan namespace System.Web.Script.Services dan class attribute [ScriptService]

using System;
using System.Collections;
using System.ComponentModel;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Web.Script.Services;

namespace JSONSample
{
    /// <summary>
    /// Summary description for WebService1
    /// </summary>
    [WebService(Namespace = "">http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    [ScriptService]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
        public Employee GetEmployee(string EmpId)
        {
            var emp = new Employee();
            emp.EmpId = EmpId;
            emp.Name = "Ahmad Masykur";
            emp.Sex = 'M';
            emp.Title = "Analyst, Application Architecture";
            return emp;
        }
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public Employee GetEmployeeJSON(string EmpId)
        {
            var emp = new Employee();
            emp.EmpId = EmpId;
            emp.Name = "Ahmad Masykur";
            emp.Sex = 'M';
            emp.Title = "Analyst, Application Architecture";
            return emp;
        }
    }
}

Berikutnya adalah buat kode javascript untuk memanggil memanggil kedua method pada WebService yang telah dibuat sebelumnya.

var displayElement1;
var displayElement2;

// Initializes global variables and session state.
function pageLoad()
{
    displayElement1 = $get("ResultId1");
    displayElement2 = $get("ResultId2");
}
function getEmployee() {
    JSONSample.WebService1.GetEmployee("894683", OnSucceeded, OnFailed);
    JSONSample.WebService1.GetEmployeeJSON("894683", OnSucceeded, OnFailed);
}

// Callback function invoked on successful
// completion of the page method.
function OnSucceeded(result, userContext, methodName)
{
    if (methodName=="GetEmployee") { // xml
        displayElement1.innerHTML = result.documentElement.selectSingleNode('//Name').text;
    }
    else { // json
        displayElement2.innerHTML = result.Name;
    }
}

// Callback function invoked on failure
// of the page method.
function OnFailed(error, userContext, methodName)
{
    if(error !== null)
    {
        displayElement.innerHTML = "An error occurred: " +
            error.get_message();
    }
}

if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

Terakhir buat halaman ASP.NET AJAX yang akan meregister JavaScript dan WebService sehingga WebService dapat dipanggil melalui JavaScript oleh ASP.NET AJAX proxy service.


<%@ Page Language="C#" AutoEventWireup="true" Inherits="System.Web.UI.Page" %> <!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 runat="server">    <title>Untitled Page</title></head><body>    <form id="form1" runat="server">    <div>        <asp:ScriptManager ID="ScriptManager1" runat="server">        <Scripts>            <asp:ScriptReference Path="~/clientscript.js" />        </Scripts>        <Services>            <asp:ServiceReference Path="~/WebService1.asmx" />        </Services>        </asp:ScriptManager>           <input type="button" value="Invoke" onclick="getEmployee()" />        <div id="ResultId1"></div>        <div id="ResultId2"></div>    </div>    </form></body></html>

Setelah dijalankan, aktifkan Web Development Helper dan check Enable Logging. Selanjutnya klik tombol Invoke tiga kali pada halaman dan periksa hasilnya.

image

Dari hasil keluaran log dapat dilihat bahwa dengan data yang sama, format XML memerlukan 226 byte sedangkan JSON hanya 132 byte. Ini jauh lebih kecil (kurang dari setengah) dibandingkan XML. Dari sisi response time, pada invoke yang pertama XML membutuhkan waktu 0:0:3430 sedangkan JSON 0:0:3280 dan invoke berikutnya untuk XML 0:0:0150 sedangkan JSON 0:0:0000. Dari data ini membuktikan bahwa JSON memang lebih ringan dibandingkan XML baik dari sisi ukuran stream yang ditransmisikan lebih kecil maupun waktu proses di server juga lebih singkat.


Tags: ,
Categories: ASP.NET AJAX | JavaScript | JSON
Permalink | Comments (15) | Post RSSRSS comment feed

Comments

Andri Mirandi Indonesia | Reply

Thursday, February 14, 2008 3:27 PM

Andri Mirandi

Menarik sekali tutorialnya mas, simple n cepet masuk ke otak..
ini nulis tutorialnya make JSON bukan XML ya ? Tong

yuinuz Indonesia | Reply

Sunday, February 24, 2008 9:12 PM

yuinuz

JSON beraarti sangat baik untuk data berukuran besar yah Mas ...

Plastic Injection Moulding Thailand | Reply

Tuesday, December 16, 2008 3:02 PM

Plastic Injection Moulding

Ahmad really thanks a lot..
I appreciate..
What is the diff b/w aspx and mspx??

zeolite | Reply

Thursday, December 18, 2008 2:42 PM

zeolite

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

Sflow Analysis United States | Reply

Friday, December 26, 2008 5:50 AM

Sflow Analysis

Thanks for the codes. Was looking for something similar. Will let you know if i face probs implementing this.

Mobile Merchant Account United States | Reply

Saturday, December 27, 2008 8:33 AM

Mobile Merchant Account

Thanks a lot for the codes. I was having problem in getting the codes to work. Your post solved a lot of questions.

Search Engine Marketing Company United States | Reply

Monday, December 29, 2008 11:27 AM

Search Engine Marketing Company

I like programming and currently learning XML.
If i can add something later i will be more than happy.

top fantasy books Sweden | Reply

Friday, January 02, 2009 12:52 AM

top fantasy books

JSON beraarti sangat baik untuk data berukuran besar yah Mas

NFL Tickets United Kingdom | Reply

Friday, January 23, 2009 1:41 PM

NFL Tickets

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.

College Football Tickets United Kingdom | Reply

Friday, January 23, 2009 1:48 PM

College Football Tickets

Java script is very easy to understand and user friendly.

Immediate Fixed Annuities United Kingdom | Reply

Saturday, January 24, 2009 6:33 PM

Immediate Fixed Annuities

thanks for java script code they useful for me and solve my problems. it is easy to me read and write.

wow accounts for sale Sweden | Reply

Friday, January 30, 2009 11:52 AM

wow accounts for sale

JSON beraarti sangat baik untuk data berukuran besar yah Mas ...

Ford Vans Qatar | Reply

Friday, January 30, 2009 8:42 PM

Ford Vans

JSON beraarti sangat baik untuk data berukuran besar yah Mas

wow accoutns Spain | Reply

Tuesday, February 03, 2009 2:50 PM

wow accoutns

JSON beraarti sangat baik untuk data berukuran besar yah Mas

Gucci Clothes United States | Reply

Tuesday, February 03, 2009 5:43 PM

Gucci Clothes

Thanks for the codes. Was looking for something similar. I will help me.

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading