zoukankan      html  css  js  c++  java
  • Json互相序列化对象

    using System.ServiceModel;
    using System.ServiceModel.Web;
    using System.Runtime.Serialization.Json;
    using System.IO;
    
    namespace Common
    {
        public class JsonUtility
        {
            public static string getJsonByObject(Object obj)
            {
                //实例化DataContractJsonSerializer对象,需要待序列化的对象类型
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                //实例化一个内存流,用于存放序列化后的数据
                MemoryStream stream = new MemoryStream();
                //使用WriteObject序列化对象
                serializer.WriteObject(stream, obj);
                //写入内存流中
                byte[] dataBytes = new byte[stream.Length];
                stream.Position = 0;
                stream.Read(dataBytes, 0, (int)stream.Length);
                //通过UTF8格式转换为字符串
                return Encoding.UTF8.GetString(dataBytes);
            }
    
            public static Object getObjectByJson(string jsonString, Object obj)
            {
                //实例化DataContractJsonSerializer对象,需要待序列化的对象类型
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                //把Json传入内存流中保存
                MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
                // 使用ReadObject方法反序列化成对象
                return serializer.ReadObject(stream);
            }
    
        }
    

      

  • 相关阅读:
    Hibernate 学习-3
    Hibernate反向工程使用心得
    MyEclipse中自动整合Spring3+Hibernate/JPA
    jsp页面不显示问题
    jstl获取当前系统时间的方法
    js实现12小时时钟
    从servlet跳到jsp页面,并用jstl 进行判断和显示方法
    jsp调用js文件时出现乱码
    常见异常总结
    js实现表单验证
  • 原文地址:https://www.cnblogs.com/shiningleo007/p/9718038.html
Copyright © 2011-2022 走看看