C#把Object对象转换成JSON串 And 读取本地Json文件转成实体类

第一种 引用System.Web.Script.Serialization.dll

 public string JsonAndObj(Object obj)
 {
     JavaScriptSerializer js = new JavaScriptSerializer();
     string myJson = js.Serialize(obj);
     return myJson;
 }

第二种  引用System.IO 和 System.Runtime.Serialization.Json.dll

public string Obj2String(object obj)
{
    string result;
    try
    {
         using (MemoryStream memoryStream = new MemoryStream())
         {
                    new DataContractJsonSerializer(obj.GetType()).WriteObject(memoryStream, obj);
                    result = Encoding.UTF8.GetString(memoryStream.ToArray());
         }
    }
    catch (Exception ex)
    {
      //DebugType dt = DebugType.err;
      //string msg = string.Format("对象JSON序列化失败,错误信息为{0}", ex.Message);
      //DebugEventArgs e = new DebugEventArgs(dt, msg);
      //Debug.OnRetrunDebug(e);
       result = "";
     }
     return result;
 }

 Json转实体 引用Json Nuge包

//读取当前项目Debug文件下的json文件
 string
str = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"XMLDemo\Team.json";

  //实体类对应的字段要和Josn文件里面的要一致 

  using (StreamReader r = new StreamReader(str, Encoding.Default))
  {
    string json = r.ReadToEnd();

    //第一种
    JavaScriptSerializer js = new JavaScriptSerializer(); 
    var list = js.Deserialize<data>(json);

    //第二种

    var data = JsonConvert.DeserializeObject<data>(json);
  }

 

posted @ 2021-11-26 16:24  寻梦人i  阅读(606)  评论(0编辑  收藏  举报