CSDN博客

img yuweiqiang

DataContractJsonSerializer是在System.ServiceModel.Web.dll中,但命名空间却是System.Runtime.Serialization.Json。

发表于2009/7/18 13:13:00  4557人阅读

分类: JSon

        //Json格式的数据  
        var data = '{"Addr":"北京市","Age":23,"Name":"张三","Password":"2342356","Tel":"6666666"}';  
         
        //转化为js对象  
        var obj = eval('('+data+')');  
          
        alert(obj.Addr); 

        //Json格式的数据
        var data = '{"Addr":"北京市","Age":23,"Name":"张三","Password":"2342356","Tel":"6666666"}';
      
        //转化为js对象
        var obj = eval('('+data+')');
       
        alert(obj.Addr);
.NET中可通过DataContractJsonSerializer来把实体转为json格式的字符串。

 需要注意这个DataContractJsonSerializer是在System.ServiceModel.Web.dll中,但命名空间却是System.Runtime.Serialization.Json。这个需要注意下。

示例代码:

 
UserInfo userInfo = new UserInfo();  
            userInfo.Name = "张三";  
            userInfo.Age = 23;  
            userInfo.Password = "2342356";  
            userInfo.Tel = "6666666";  
            userInfo.Addr = "北京市";  
 
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(UserInfo));  
            System.IO.MemoryStream ms = new System.IO.MemoryStream();  
            serializer.WriteObject(ms,userInfo);  
            System.IO.StreamReader reader = new System.IO.StreamReader(ms);  
            ms.Position = 0;  
            string res = reader.ReadToEnd();  
            reader.Close();  
            ms.Close();  
 
            Console.WriteLine(res); 


UserInfo userInfo = new UserInfo();
            userInfo.Name = "张三";
            userInfo.Age = 23;
            userInfo.Password = "2342356";
            userInfo.Tel = "6666666";
            userInfo.Addr = "北京市";

            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(UserInfo));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            serializer.WriteObject(ms,userInfo);
            System.IO.StreamReader reader = new System.IO.StreamReader(ms);
            ms.Position = 0;
            string res = reader.ReadToEnd();
            reader.Close();
            ms.Close();

            Console.WriteLine(res);
虽然网上的资料有说实体类必须标准[DataContract]属性,成员必须标准[DataMember]才可以实例化,但MSDN上没有这么说,并且我上面的代码没标注,也依旧序列化了。

0 0

相关博文

我的热门文章

img
取 消
img