hashtable 转 json

zhuan:https://www.cnblogs.com/sntetwt/p/3500740.html

代码如下:

ArrayList eventList = new ArrayList();
            
            for (int i = 0; i < 3;i++ )
            {
                Hashtable ht = new Hashtable();
                ht.Add("eventid",i+1);
                ht.Add("eventname","圣诞节");
                ht.Add("eventdate","2012-12-25");
                ht.Add("eventlocation","公司会议中心");
                eventList.Add(ht);
            }
            JavaScriptSerializer ser = new JavaScriptSerializer();
            String jsonStr=ser.Serialize(eventList);
            Response.Write(jsonStr);
 
 

查看页面,可以看到返回的结果是JSON格式的数据。实际上是一个数组,数组里面每项是一个json对象。

[{"eventdate":"2012-12-25","eventlocation":"公司会议中心","eventname":"圣诞节","eventid":1},{"eventdate":"2012-12-25","eventlocation":"公司会议中心","eventname":"圣诞节","eventid":2},{"eventdate":"2012-12-25","eventlocation":"公司会议中心","eventname":"圣诞节","eventid":3}]

我们可以通过这个网址验证生成的json是否正确。http://jsonlint.com/

但是我们需要注意的是,hashtable在存放数据时是无序的,所以数据并不是按照我们插入的先后顺序显示的。我们可能期望的数据格式是:

{"eventid":1","eventname":"圣诞节",eventdate":"2012-12-25","eventlocation":"公司会议中心"}

但是我们查看我们的结果不是这样的,但是数据返回给前端之后,还是要通过JSON.parse()方法转换为json对象,所以不按照特定的顺序,对我们开发不影响。

数据在HTTP协议上传输都是使用二级制流,所以数据到达客户端,需要通过JSON.parse()。我的项目是Windows8

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将 C# 的 Hashtable 进行序列化,可以使用 .NET 中自带的 BinaryFormatter 类或者 Json.NET 库。 使用 BinaryFormatter 类进行序列化: ```csharp using System.IO; using System.Runtime.Serialization.Formatters.Binary; Hashtable hashtable = new Hashtable(); // 在 hashtable 中添加一些键值对 BinaryFormatter formatter = new BinaryFormatter(); using (Stream stream = new FileStream("hashtable.bin", FileMode.Create, FileAccess.Write, FileShare.None)) { formatter.Serialize(stream, hashtable); } ``` 使用 BinaryFormatter 类进行反序列化: ```csharp using System.IO; using System.Runtime.Serialization.Formatters.Binary; Hashtable hashtable = null; BinaryFormatter formatter = new BinaryFormatter(); using (Stream stream = new FileStream("hashtable.bin", FileMode.Open, FileAccess.Read, FileShare.Read)) { hashtable = (Hashtable)formatter.Deserialize(stream); } ``` 使用 Json.NET 库进行序列化: ```csharp using Newtonsoft.Json; Hashtable hashtable = new Hashtable(); // 在 hashtable 中添加一些键值对 string json = JsonConvert.SerializeObject(hashtable, Formatting.Indented); File.WriteAllText("hashtable.json", json); ``` 使用 Json.NET 库进行反序列化: ```csharp using Newtonsoft.Json; Hashtable hashtable = null; string json = File.ReadAllText("hashtable.json"); hashtable = JsonConvert.DeserializeObject<Hashtable>(json); ``` 需要注意的是,如果 Hashtable 中的值类型是自定义类型,那么在反序列化时需要确保该类型已经被加载。另外,因为 Hashtable 是不支持序列化的,所以在序列化时需要将其换为支持序列化的类型,比如 Dictionary。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值