日期:2014-05-18  浏览次数:21200 次

json反序列化失败
定义一个类
public class CREC
  {
  public int i;
  public string s;
  public DataTable dt;
  }




SqlConnection conn = new SqlConnection("Server=127.0.0.1;database=test ;uid=sa;pwd=");
  SqlCommand cmd = new SqlCommand("select * from t1", conn);
  SqlDataAdapter adapter = new SqlDataAdapter(cmd);
  DataSet ds = new DataSet();
  DataTable dt=new DataTable();
  adapter.Fill(dt);
  ds.Tables.Add(dt);
   

  CREC rec = new CREC();
  rec.i = 10;
  rec.s = "abc";
  rec.dt = dt.Copy();

  string sJSON = JsonConvert.SerializeObject(rec);
  MessageBox.Show(sJSON);

  //这里反序列化失败
  CREC recOut = JsonConvert.DeserializeObject<CREC>(sJSON);

------解决方案--------------------
C# code
        /// <summary>
        /// Serialize object to string of json format
        /// </summary>
        private string JsonSerializer<T>(T t)
        {
            var ser = new DataContractJsonSerializer(typeof(T));
            var ms = new MemoryStream();
            ser.WriteObject(ms, t);
            string jsonString = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();
            return jsonString;
        }

        /// <summary>
        /// Deserialize string of json format to object
        /// </summary>
        private T JsonDeserialize<T>(string jsonString)
        {
            var ser = new DataContractJsonSerializer(typeof(T));
            var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            var obj = (T)ser.ReadObject(ms);
            return obj;
        }

------解决方案--------------------
不懂帮顶! 我记得看过一些视频 如果转换出现问题最好转换成数组之后再序列化 具体什么情况忘记了。。