tags:

views:

1671

answers:

8

Why should I use JSON with ASP.NET? Can you give a practical example? I have read articles but not so good.

A: 

JSON is way easier to parse than XML, and there are a lot of options to do so.

Otávio Décio
+2  A: 

How about when returning data from a Web Service ? Here are two methods that are suitable for .Net 2.0, that take a DataTable or a DataRow Parameter, and return a JSON formatted string to be sent over to the client, from the web service:

public string GetJson(DataRow r)
    {
        int index = 0;
        StringBuilder json = new StringBuilder();
        foreach (DataColumn item in r.Table.Columns)
        {
            json.Append(String.Format("\"{0}\" : \"{1}\"", item.ColumnName, r[item.ColumnName].ToString().Replace("\"","\\\"")));
            if (index < r.Table.Columns.Count - 1)
            {
                json.Append(", ");
            }
            index++;
        }
        return "{" + json.ToString() + "}";
    }

public string GetJson(DataTable t)
{
    int index = 0;
    StringBuilder json = new StringBuilder();
    foreach (DataRow currRow in t.Rows)
    {
        json.Append(GetJson(currRow));
        if (index < t.Rows.Count - 1)
        {
            json.Append(", ");
        }
    }
    return "[" + json.ToString() + "]";
}

The result can then be sent and evaluated on the Client.

Andreas Grech
+2  A: 

JSON is good for adding Ajax functionality. For example you can populate the contents of a ComboBox with some values returned by an Ajax request returning a JSON object.

ASP.NET Ajax uses JSON internally. If you are using another framework, like jQuery, you do both the client and server side yourself.

JSON is easy to read by both humans and computers and introduces little overhead. JavaScript client code can natively parse JSON.

kgiannakakis
A: 

It's a way to directly inject javascript objects, accessible in all your other client side script, using OOP notation, into your web page, with no parsing or processing required on the client side.

Charles Bretana
+1  A: 

Use JSON because it's very easy to parse in the browser- just call eval() and you're pretty much done.

As long as we're sharing DataTable to JSON implementations:

    public static string DataTableToJSON(DataTable dt)
    {
        string rowDelimiter = "";

        StringBuilder result = new StringBuilder("[");
        foreach (DataRow row in dt.Rows)
        {
            result.Append(rowDelimiter);
            result.Append(DataRowToJSON(row));
            rowDelimiter = ",";
        }
        result.Append("]");

        return result.ToString();
    }

    public static string DataRowToJSON(DataRow row)
    {
        DataColumnCollection cols = row.Table.Columns;
        string colDelimiter = "";

        StringBuilder result = new StringBuilder("{");       
        for (int i = 0; i < cols.Count; i++)
        { // use index rather than foreach, so we can use the index for both the row and cols collection
            result.AppendFormat("{0}\"{1}\":{2}",
                    colDelimiter, cols[i].ColumnName,
                    PrepJSONValue(row[i], cols[i].DataType));

            colDelimiter = ",";
        }
        result.Append("}");
        return result.ToString();
    }

    // possible types:
    // http://msdn.microsoft.com/en-us/library/system.data.datacolumn.datatype(VS.80).aspx
    private static Type[] numeric = new Type[] {typeof(byte), typeof(decimal), typeof(double), 
                                     typeof(Int16), typeof(Int32), typeof(SByte), typeof(Single),
                                     typeof(UInt16), typeof(UInt32), typeof(UInt64)};

    private static long EpochTicks = new DateTime(1970, 1, 1).Ticks;

    private static string PrepJSONValue(object value, Type DataType)
    {
        // null
        if (value == DBNull.Value) return "null";

        // numeric
        if (Array.IndexOf(numeric, DataType) > -1)
            return value.ToString(); // TODO: eventually want to use a stricter format

        // boolean
        if (DataType == typeof(bool))
            return ((bool)value) ? "true" : "false";

        // date -- see http://weblogs.asp.net/bleroy/archive/2008/01/18/dates-and-json.aspx
        if (DataType == typeof(DateTime))       
            return "\"\\/Date(" + new TimeSpan(((DateTime)value).ToUniversalTime().Ticks - EpochTicks).TotalMilliseconds.ToString() + ")\\/\"";

        // TODO: add Timespan support
        // TODO: add Byte[] support

        // string/char
        return "\"" + value.ToString().Replace(@"\", @"\\").Replace(Environment.NewLine, @"\n").Replace("\"", @"\""") + "\"";
    }
Joel Coehoorn
Instead of eval(), it's always better to use Crockford's library: http://www.json.org/js.html
Andreas Grech
A: 

What are your alternatives? XML is heavier than JSON, so it uses more bandwidth (but powerful for validating and transforming data), YAML requires indentation and newlines, making it a suboptimal format for sending over Http (but good for storing logs, data,and configs). JSON is native javascript, and light, so it's great on the client side and for transmitting over Http

Robert Gould
+1  A: 

There are a lot of uses, APIs, web services, and it has much less overhead than XML. As practical example, you can fill an ExtJs tree or grid using JSON data with a few lines of code.

If you're using ASP.NET MVC it's really easy to return JSON from a controller, something like this:

// this method return JSON directly
public JsonResult GetData() {

    data = LoadData(); // load the data from a database or a service
    return Json(data); // will serialize your data object as JSON

}
Eduardo Campañó
+1  A: 

An Ajax call that returns a JSON object can be converted into a JavaScript object trivially, e.g.

var jsObject = eval( "(" + ajaxCallReturningJson(whatever) + ")" );

This makes it very convenient for passing complex data to the client without having to make a custom representation or fool around with XML/XSLT.

Steven A. Lowe