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

    /// <summary> 
    /// 将实体类转换为json数据
    /// </summary> 
    /// <returns></returns> 
    public string getJsonInfo()
    {
    
    BillPostModel model = new BillPostModel();
    model.amount =12;
    model.cid ="1";
    model.id = "2";
    model.payment_date ="2017-09-09";
    model.remark = "测试";
    model.sample_id = "1";
    //将对象序列化json 
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(BillPostModel));    //注意这里是实体类 类名
    //创建存储区为内存流 
    System.IO.MemoryStream ms = new MemoryStream();
    //将json字符串写入内存流中 
    serializer.WriteObject(ms, model);
    System.IO.StreamReader reader = new StreamReader(ms);
    ms.Position = 0;
    string strRes = reader.ReadToEnd();
    reader.Close();
    ms.Close();
    return strRes;
    }
    
    
    
    
    
    /// <summary>
    /// 把Json文本转为实体
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="input"></param>
    /// <returns></returns>
    public static T FromJSON<T>(string input)
    {
    try
    {
    
     //{"IP":"58.215.186.139", "CPU":"0.0%", "AllMem":"256 G","RemainMem":"217.2 G","UserdMem":"38.8 G [ 15.15625% ]",  "download":"267.57 kbps"  ,"upload":"18.00 kbps" ,"runtime":"61-19-34" ,"OS":"Microsoft Windows NT 6.1.7601 Service Pack 1","Disk":"C:RemainDisk:22.1G,AllDisk:50.0G|D:RemainDisk:110.6G,AllDisk:182.3G|E:RemainDisk:399.7G,AllDisk:837.7G|" ,"t":"2019-03-29 17:18:14"  ,"rundt":"2019-01-27 21:43:42"}
    return JsonConvert.DeserializeObject<T>(input);
    }
    catch (Exception ex)
    {
    return default(T);
    }
    }
  • 相关阅读:
    Spring(四)
    安卓学习25(BaseAdapter优化)
    安卓学习24(Adapter)
    每周总结(4.4)
    安卓学习23(Date & Time组件)
    安卓学习22(Date & Time组件)
    安卓学习21(ScrollView(滚动条))
    安卓学习20(RatingBar(星级评分条))
    每周总结(3.28)
    安卓学习19(SeekBar(拖动条))
  • 原文地址:https://www.cnblogs.com/bin521/p/8296649.html
Copyright © 2011-2022 走看看