0
点赞
收藏
分享

微信扫一扫

C# Json无法反序列化

火热如冰 2022-04-19 阅读 77
c#
 public class PgToolGroup : IDisposable
 {
        public PgToolGroup(ProjectData project)
        {
            GroupName = project.GenDefaultName();
        }
}

原本无法序列化代码

 public class PgToolGroup : IDisposable
 {
        public PgToolGroup(ProjectData project)
        {
            GroupName = project.GenDefaultName();
        }

        public PgToolGroup()
        {
        }
}

可以正常序列化代码

封装的Json序列化函数

  public T ReadJsonConfig<T>(string jsonPath)
   {
      StreamReader sr = File.OpenText(jsonPath);
      string jsonWordTemplate = sr.ReadToEnd();
      sr.Close();
      return JsonConvert.DeserializeObject<T>(jsonWordTemplate);
  }

   public void WriteJsonConfig(object info, string jsonPath)
   {
      try
      {
          string objectsJsonStr = JsonConvert.SerializeObject(info);
          File.WriteAllText(jsonPath, objectsJsonStr);
      }
      catch
      {
         Console.WriteLine("error");
       }
   }

    public  List<T> ReadJsonConfigList<T>(string jsonPath)
    {
            StreamReader sr2 = File.OpenText(jsonPath);
            string jsonWordTemplate = sr2.ReadToEnd();
            sr2.Close();
            object o = JsonConvert.DeserializeObject(jsonWordTemplate, typeof(List<T>));
            List<T> list = o as List<T>;
            return list;
    }

     public void WriteJsonConfigList<T>(List<T> info, string jsonPath)
     {
            try
            {
                JsonSerializer serializer = new JsonSerializer();
                StringWriter sw = new StringWriter();
                serializer.Serialize(new JsonTextWriter(sw), info);
                string result = sw.GetStringBuilder().ToString();
                File.WriteAllText(jsonPath, result);
            }
            catch
            {
                Console.WriteLine("error");
            }
     }

总结问题点:做序列化的类 要创建无惨构造函数

举报

相关推荐

0 条评论