ASP. NET JSON Example code for converting strings to entity classes

  • 2020-09-28 08:51:24
  • OfStack

Let's wrap up a class first! This class can be found on the Internet! If I have this class, everything is going to be easy. Haha.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization.Json;
using System.ServiceModel.Web;/// Remember to refer to this namespace 
using System.IO;
using System.Text;
/// <summary>
/// Summary description for JsonHelper
/// </summary>
public class JsonHelper
{
    public JsonHelper()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    /// <summary>
    ///  Serialize an object  JSON  string  
    /// </summary>
    /// <typeparam name="T"> Object type </typeparam>
    /// <param name="obj"> Object entities </param>
    /// <returns>JSON string </returns>
    public static string GetJson<T>(T obj)
    {
        // Keep in mind that   Add reference  System.ServiceModel.Web 
        /**
         *  If you don't add the above reference ,System.Runtime.Serialization.Json; Json I can't get out of here 
         * */
        DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
        using (MemoryStream ms = new MemoryStream())
        {
            json.WriteObject(ms, obj);
            string szJson = Encoding.UTF8.GetString(ms.ToArray());
            return szJson;
        }
    }
    /// <summary>
    ///  the JSON String is restored to an object 
    /// </summary>
    /// <typeparam name="T"> Object type </typeparam>
    /// <param name="szJson">JSON string </param>
    /// <returns> Object entities </returns>
    public static T ParseFormJson<T>(string szJson)
    {
        T obj = Activator.CreateInstance<T>();
        using (MemoryStream ms = new MemoryStream (Encoding.UTF8.GetBytes(szJson)))
        {
            DataContractJsonSerializer dcj = new DataContractJsonSerializer(typeof(T));
            return (T)dcj.ReadObject(ms);
        }
    }
}

Test entity class:

public class TestData
{
    public TestData()
    {
    }
    public int Id { get; set; }
    public string Name { get; set; }
    public string Sex { get; set; }
}

Test page:

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        string jsonStr = string.Empty;
        List<TestData> tds = new List<TestData>();
        // The test data 
        for (int i = 1; i < 4; i++)
        {
            tds.Add(new TestData() { Id = i, Name = "jinho" + i, Sex = "male" });
        }        // the 1 a list convert json string 
        jsonStr = JsonHelper.GetJson<List<TestData>>(tds);
        Response.Write(jsonStr);
        this.Page.ClientScript.RegisterStartupScript(this.GetType(), "json", "getJson(" + jsonStr + ");", true);
    }

</script>
<script type="text/javascript">
    function getJson(jsonStr) {        // use eval function 
        var json = eval(jsonStr);         // Because the top is list A collection of 
        for (var i = 0; i < json.length; i++) {
            alert(json[i].Id + "Name:" + json[i].Name);
        }
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    </div>
    </form>
</body>
</html>

Test yourself on converting json strings to entities! As long as there is the above JsonHelper class, 1 cut is easy to do!


Related articles: