Why should I use JSON with ASP.NET?

Why should I use JSON with ASP.NET? Can you give a practical example? I read articles, but not very well.

+6
json
source share
9 answers

How about when it returns data from a web service ? Here are two methods that are suitable for .NET 2.0 that use a DataTable or DataRow Parameter and return a formatted JSON string to send 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() + "]"; } 

Then the result can be sent and evaluated by the client.

+2
source share

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

ASP.NET Ajax uses JSON internally. If you use another framework, for example jQuery, you yourself do both the client and the server.

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

+2
source share

Use JSON because it is very easy to parse in the browser - just call eval() and you pretty much did.

For now, we are using DataTable to implement JSON:

  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("\"", @"\""") + "\""; } 
+1
source share

There are many uses, APIs, web services, and it has much less overhead than XML. As a practical example, you can populate the ExtJs tree using JSON data with several lines of code.

If you use ASP.NET MVC, it is very easy to return JSON from the 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 } 
+1
source share

An Ajax call that returns a JSON object can be converted to a JavaScript object trivially, for example.

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

This makes it very convenient to transfer complex data to the client without having to create a custom view or spoof XML / XSLT.

+1
source share

JSON is easier to parse than XML, and there are many options for this.

0
source share

This is a way to directly embed javascript objects available on all of your other client side script using OOP notation on your web page, without the processing or processing required on the client side.

0
source share

What are your alternatives? XML is heavier than JSON, so it uses a lot of bandwidth (but powerful for checking and converting data), YAML requires indentation and new lines, which makes it suboptimal for sending via Http (but useful for storing logs, data and configs). JSON is built-in javascript and lightweight, so it is excellent on the client side and for sending over Http

0
source share

Here is a very good article on why JSON is the preferred method for sending and receiving data.

http://robtiffany.com/windows-phone-7/windows-phone-7-line-of-business-app-dev-building-a-wcf-rest-json-service

0
source share

All Articles