今天遇到在后台中要获取json格式数据里的某些值,网上查了些资料:

 string jsonstr = _vCustomerService.LoadCustomerbyNumTotalData(queryParam, out total);
//[{"ROWID":0,"BUYNUM":"1","CUSTOMERCOUNT":"26"},{"ROWID":1,"BUYNUM":"5","CUSTOMERCOUNT":"1"},
//{"ROWID":2,"BUYNUM":"","CUSTOMERCOUNT":"4679359"}]

  这时候用MVC3自带的类库进行解析:using System.Web.Script.Serialization;

先构造实体类

[Serializable]
[DataContract]//得在定义对象类前,先声明这两个属性
public partial class BuyNumQueryParam
{
public string ROWID { get; set; }
public string BUYNUM { get; set; }
public string CUSTOMERCOUNT { get; set; }
}

  

JavaScriptSerializer js = new JavaScriptSerializer();
List<BuyNum> list = js.Deserialize<List<BuyNum>>(jsonstr);

以上是对数据的反序列化,那么数据的序列化该怎么做呢??

很简单 ,看下面一段代码:

JavaScriptSerializer serializer = new JavaScriptSerializer();
result.TableData = serializer.Serialize(result.InputContentList);

只要调用JavaScriptSerializer的Serialize方法就可以对数据进行序列化,最后得到一个string型的json数据。

05-08 08:12