Json Class

Provides methods for working with data in JavaScript Object Notation (JSON) format.

System.Object
  System.Web.Helpers.Json

Namespace:  System.Web.Helpers
Assembly:  System.Web.Helpers (in System.Web.Helpers.dll)

public static class Json

The Json type exposes the following members.

  NameDescription
Public methodStatic memberDecode(String)Converts data in JavaScript Object Notation (JSON) format into a data object.
Public methodStatic memberDecode(String, Type)Converts data in JavaScript Object Notation (JSON) format into a data object of a specified type.
Public methodStatic memberDecode<T>(String)Converts data in JavaScript Object Notation (JSON) format into the specified strongly typed data list.
Public methodStatic memberEncodeConverts a data object to a string that is in the JavaScript Object Notation (JSON) format.
Public methodStatic memberWriteConverts a data object to a string in JavaScript Object Notation (JSON) format and adds the string to the specified TextWriter object.
Top

This class represents a helper, which is a component that simplifies web programming in ASP.NET Web Pages. You can use the Json class to encode or decode data in JSON format.

HTTP requires structured data to be converted, or serialized, to a format that can be read across the web by different processes. Popular serialization formats are JSON and XML, which are both are text-based formats. A typical use for the JSON format is to retrieve data from a database, a web service, or other sources, encode it in JSON format, and then return it to a requesting browser as part of a web page.

For example, after you retrieve data using a query in ASP.NET Razor code, you can call Encode(Object) to encode the data from the query and assign the results to a JavaScript variable in a client code block. In the browser, after you get the web page that contains the JSON data, you can use JavaScript code to manipulate how the data is displayed in the browser without sending additional requests to the server. You can also provide controls and code that enable users to update the data and then post it to a web server.

In ASP.NET and Razor pages, you typically use the JavaScript-based jQuery or ASP.NET Ajax libraries for client-side data manipulation. These libraries provide an extensive infrastructure that helps you build pages that perform client-side data manipulation using JavaScript, with minimal round trips to a server.

When users have finished viewing the page that contains the data, they can submit the page. In the server-side page code, when you receive posted JSON data, you can use the Decode(String) method to convert the data from JSON format into a data object. You can then use code (for example, a foreach loop) to process the posted data and perform tasks such as updating a database, displaying the updated data on the page, or serving the data to other requests by using a web service.

The following example shows how to retrieve data from a database, encode it using the Json class, and then send it to a browser inside a JavaScript block. The page uses JavaScript to enable users to update the product names in an HTML form without additional requests to the server. After a user submits the updated product names, the page receives the updated JSON-encoded data in code on the server and calls the Decode(String) method to render the data as an object. The updated data, including any product names that have been updated by the user, is then displayed in the page by using a foreach loop to create a table.


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>JSON Helper</title>
        <script type="text/javascript">
            // This function receives a JSON-encoded string passed by the server, and 
            // then creates a dynamic HTML form that displays the product names in editable fields.
            function WriteData(theData) {
               var i; 
               document.write("<form method='post' name='productsForm' action=''>");
               document.write("<input type='hidden' name='jsonDataField' id='jsonDataField' value='" + JSON.stringify(theData) + "' />");
               for(i in theData) 
                {
                  document.write("<input type='text' name='productName' id='" + theData[i].Id + "' value='" + theData[i].Name + "' /></br>");
                }
                document.write("<input type='submit' id='submit' value='Update Product Names' onclick='UpdateProductNames()' />");
            }

            // After a user updates a product name and clicks the Update button, this function updates 
            // the hidden field value that contains the JSON-encoded data and sends it to the server.
            function UpdateProductNames() {
                var i, x;
                var counter = 0;
                // Create an array of input elements that contain product names.
                var inputElements = document.getElementsByTagName("input");
                var prodNames = [];
                for(i = 0; i < inputElements.length; i++) {
                    if(inputElements[i].name == "productName") {
                        prodNames[counter] = inputElements[i];
                        counter++;
                     }
                 }
                // Use the DOM parse method to convert JSON data to an object, for easier looping.
                var updatedJsonData = JSON.parse(document.getElementById("jsonDataField").value);
                // Add the values from the productName elements to the JSON data.
                for(i in prodNames) {
                    for(x in updatedJsonData) {
                        if(prodNames[i].id == updatedJsonData[x].Id) {
                            updatedJsonData[x].Name = prodNames[i].value;
                            break;
                         }
                     }
                 }
                // After updating the form data with the user's changes, use the DOM stringify method
                // to convert the JSON data back to a JSON-encoded string, for posting to the server.
                document.getElementById("jsonDataField").value = JSON.stringify(updatedJsonData);
                // Submit the updated data to the server.
                document.getElementById("submit").submit();
             }
  </script>
    </head>
    <body>
        @{
          // If this is the initial page request, get the data and add to a form.
          if(!IsPost) {
            var db = Database.Open("bakery");
            var products = db.Query("SELECT * FROM PRODUCTS").ToList();
            // JSON.Encode converts data to a JSON-encoded string, which we can 
            // send to the browser in an HTML form or JavaScript.
            var JsonString = Json.Encode(products);
            <text>
            <script type="text/javascript">
              // Use Html.Raw to pass the JSON-encoded data in literal form to a JavaScript function.
              WriteData(@Html.Raw(JsonString));
            </script> 
            </text>
           } 
           else {
            // If the page is a postback, display the user's updated data in a table.
            <text>
            <h2>JSON-decoded Data Posted by a User</h2>
            <table border="1">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Description</th>
                        <th>Price</th>
                    </tr>
                </thead>
               <tbody> 
                @foreach(var p in Json.Decode(Request["jsonDataField"])) {
                 <tr>
                    <td>@p.Name</td>
                    <td>@p.Description</td>
                    <td>@p.Price</td>
                 </tr>
                 }
                 </tbody>
            </table>
            </text>
            }
        }
    </body>
</html>


Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show: