zoukankan      html  css  js  c++  java
  • 实体和json互转

    1.实体转Json

    需要添加引用:System.ServiceModel.Web 和 System.Runtime.Serialization,然后使用Using:

      /// <summary>
            /// 获取将实体类转换为json数据(目的是为了更快在网页上传递数据)
            /// </summary>
            /// <returns></returns>
            public string GetJsonInfo(DatasModel dm)
            {
                //将对象序列化json
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DatasModel));
                //创建存储区为内存流
                System.IO.MemoryStream ms = new MemoryStream();
                //将json字符串写入内存流中
                serializer.WriteObject(ms, dm);
                System.IO.StreamReader reader = new StreamReader(ms);
                ms.Position = 0;
                string strRes = reader.ReadToEnd();
                reader.Close();
                ms.Close();
                return strRes;
            }

    2.json转实体

    ExtractModel为测试实体

    public static ExtractModel DeserializeJsonToObjectss<ExtractModel>(string json) where ExtractModel : class
    {
        try
        {
            JsonSerializer serializer = new JsonSerializer();
            StringReader sr = new StringReader(json);
            object o = serializer.Deserialize(new JsonTextReader(sr), typeof(ExtractModel));
    
    
            ExtractModel t = o as ExtractModel;
            return t;
        }
        catch (Exception ex)
        {
            return null;
        }
  • 相关阅读:
    Something about the "BSTR" and "SysStringLen"
    关于 i = i ++ 的问题
    duilib写个三国杀?
    关于WM_GETTEXT的应用
    hoops暂时用过的一些方法
    Hoops随便记的
    C++ win32线程数上限
    windows系统时间(SYSTEMTIME)
    Form表单提交的那些事
    多行文字溢出...
  • 原文地址:https://www.cnblogs.com/yuanshuo/p/13038873.html
Copyright © 2011-2022 走看看