ASP.NET自帶對象JSON字符串與實體類的轉(zhuǎn)換
來源:易賢網(wǎng) 閱讀:1140 次 日期:2016-08-05 15:00:16
溫馨提示:易賢網(wǎng)小編為您整理了“ASP.NET自帶對象JSON字符串與實體類的轉(zhuǎn)換”,方便廣大網(wǎng)友查閱!

關(guān)于JSON的更多介紹,請各位自行g(shù)oogle了解!如果要我寫的話,我也是去Google后copy!嘿嘿,一直以來很想學習json,大量的找資料和寫demo,總算有點了解! 切入正題!

還是先封裝一個類吧! 這個類網(wǎng)上都可以找到的!有個這個類,一切都將變得簡單了。

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Runtime.Serialization.Json;

using System.ServiceModel.Web;///記得引用這個命名空間

using System.IO;

using System.Text;

/// <summary>

/// Summary description for JsonHelper

/// </summary>

public class JsonHelper

{

  public JsonHelper()

  {

    //

    // TODO: Add constructor logic here

    //

  }

  /// <summary>

  /// 把對象序列化 JSON 字符串 

  /// </summary>

  /// <typeparam name="T">對象類型</typeparam>

  /// <param name="obj">對象實體</param>

  /// <returns>JSON字符串</returns>

  public static string GetJson<T>(T obj)

  {

    //記住 添加引用 System.ServiceModel.Web 

    /**

     * 如果不添加上面的引用,System.Runtime.Serialization.Json; Json是出不來的哦

     * */

    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>

  /// 把JSON字符串還原為對象

  /// </summary>

  /// <typeparam name="T">對象類型</typeparam>

  /// <param name="szJson">JSON字符串</param>

  /// <returns>對象實體</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);

    }

  }

}

測試實體類: 

public class TestData

{

  public TestData()

  {

  }

  public int Id { get; set; }

  public string Name { get; set; }

  public string Sex { get; set; }

測試頁面: 

<%@ 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>();

    //測試數(shù)據(jù)

    for (int i = 1; i < 4; i++)

    {

      tds.Add(new TestData() { Id = i, Name = "jinho" + i, Sex = "male" });

    }    //把一個list轉(zhuǎn)換為json字符串

    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) {    //使用eval函數(shù)

    var json = eval(jsonStr);     //因為上面為list集合

    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>

關(guān)于json字符串轉(zhuǎn)換為實體請各位自己測試吧!只要有上面那個JsonHelper 類,一切都好辦!

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助

更多信息請查看網(wǎng)絡編程
易賢網(wǎng)手機網(wǎng)站地址:ASP.NET自帶對象JSON字符串與實體類的轉(zhuǎn)換
關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 加入群交流 | 手機站點 | 投訴建議
工業(yè)和信息化部備案號:滇ICP備2023014141號-1 云南省教育廳備案號:云教ICP備0901021 滇公網(wǎng)安備53010202001879號 人力資源服務許可證:(云)人服證字(2023)第0102001523號
聯(lián)系電話:0871-65317125(9:00—18:00) 獲取招聘考試信息及咨詢關(guān)注公眾號:hfpxwx
咨詢QQ:526150442(9:00—18:00)版權(quán)所有:易賢網(wǎng)