服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服务器之家 - 编程语言 - ASP.NET教程 - ASP.NET自带对象JSON字符串与实体类的转换

ASP.NET自带对象JSON字符串与实体类的转换

2020-01-21 14:28JoinJ ASP.NET教程

这篇文章主要介绍了ASP.NET自带对象JSON字符串与实体类的转换,感兴趣的小伙伴们可以参考一下

关于JSON的更多介绍,请各位自行google了解!如果要我写的话,我也是去Google后copy!嘿嘿,一直以来很想学习json,大量的找资料和写demo,总算有点了解! 切入正题!

还是先封装一个类吧! 这个类网上都可以找到的!有个这个类,一切都将变得简单了,哈哈。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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);
    }
  }
}

测试实体类: 

?
1
2
3
4
5
6
7
8
9
public class TestData
{
  public TestData()
  {
  }
  public int Id { get; set; }
  public string Name { get; set; }
  public string Sex { get; set; }
}

测试页面: 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<%@ 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>();
    //测试数据
    for (int i = 1; i < 4; i++)
    {
      tds.Add(new TestData() { Id = i, Name = "jinho" + i, Sex = "male" });
    }    //把一个list转换为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函数
    var json = eval(jsonStr);     //因为上面为list集合
    for (var i = 0; i < json.length; i++) {
      alert(json[i].Id + "Name:" + json[i].Name);
    }
  }
</script>
<head runat="server">
  <title></title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
  
  </div>
  </form>
</body>
</html>

关于json字符串转换为实体请各位自己测试吧!只要有上面那个JsonHelper 类,一切都好办!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

延伸 · 阅读

精彩推荐