Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use JSON with ASP.NET?

Tags:

json

asp.net

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

like image 419
Viks Avatar asked Jan 15 '09 14:01

Viks


People also ask

What is the main purpose of JSON?

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).

What is the use of JSON in ASP NET MVC?

It is a data interchange medium and is very lightweight. It is one kind of syntax for storing and passing data. Since it is Javascript object notation, it uses the javascript style of syntax, but actually is text only.

What is JSON asp net?

json file. This file is using JavaScript object notation to store configuration information and it is this file that is really the heart of a . NET application. Without this file, you would not have an ASP.NET Core project. Here, we will discuss some of the most important features of this file.

Why do we prefer JSON over XML?

JSON is faster because it is designed specifically for data interchange. JSON encoding is terse, which requires less bytes for transit. JSON parsers are less complex, which requires less processing time and memory overhead. XML is slower, because it is designed for a lot more than just data interchange.


1 Answers

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.

like image 51
Andreas Grech Avatar answered Sep 28 '22 00:09

Andreas Grech