zoukankan      html  css  js  c++  java
  • JSON序列化和反序列化

    public class JSONHelper
        {
            public static string Serialize<T>(T obj)//序列化为JSON
            {
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
                MemoryStream ms = new MemoryStream();
                serializer.WriteObject(ms, obj);
                string retVal = Encoding.Default.GetString(ms.ToArray());
                return retVal;
            }
    
            public static T Deserialize<T>(string json)//反序列化为对象
            {
                T obj = Activator.CreateInstance<T>();
                MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
                obj = (T)serializer.ReadObject(ms);
                ms.Close();
                return obj;
            }
            public static List<T> DeserializeToList<T>(string json)//反序列化成泛型
            {
    
                JavaScriptSerializer serializer = new JavaScriptSerializer();
    
                List<T> objs = serializer.Deserialize<List<T>>(json);
    
                return objs;
    
            }
        }
    JavaScriptSerializer 需添加system.web.Extensions引用
  • 相关阅读:
    Laravel 出现 No application encryption key has been specified.
    windows下用composer局部安装laravel
    vue组件--通讯录
    vue组件--TagsInput
    axios封装(二)队列管理
    axios封装(一)基础配置
    [git hooks] pre-commit 配置
    qs.js
    flexbox的应用
    盒子模型详解
  • 原文地址:https://www.cnblogs.com/toloe/p/4503551.html
Copyright © 2011-2022 走看看