我有一个需求.需要序列化字符串
static byte[] Serialize(object data) { byte[] body; var serializer = new Newtonsoft.Json.JsonSerializer(); using (var ms = new MemoryStream()) { using (var sw = new StreamWriter(ms, Encoding.UTF8)) { using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw)) { writer.Formatting = Newtonsoft.Json.Formatting.Indented; serializer.Serialize(writer, data); sw.Flush(); body = ms.ToArray(); } } } return body; //BinaryFormatter formatter = new BinaryFormatter(); //MemoryStream rems = new MemoryStream(); //formatter.Serialize(rems, data); //return rems.GetBuffer(); }
然后.怎么再把这个 byte[] 还原成对像呢??
以下代码不可以还原.....
static object Deserialize(byte[] data) {
using (var ms = new MemoryStream(data)) { using (var sw = new StreamReader(ms, Encoding.UTF8)) { using (Newtonsoft.Json.JsonReader jr = new Newtonsoft.Json.JsonTextReader(sw)) { var t = serializer.Deserialize(jr); return t; } } }
// var serializer = new Newtonsoft.Json.JsonSerializer(); // serializer.Deserialize() //BinaryFormatter formatter = new BinaryFormatter(); //MemoryStream rems = new MemoryStream(data); //data = null; //return formatter.Deserialize(rems); }
通过data参数得到一个JsonReader对象,然后JSONSerializer.Deserialize<T>(JsonReader);
高分蹭分,有Serialize,找相应的Deserialize。。。
var serializer = new Newtonsoft.Json.JsonSerializer();
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream rems = new MemoryStream(data);
data = null;
return serializer.Deserialize(formatter.Deserialize(rems));
这个是不行的.
不能直接反序列化 object
@luckdv: return serializer.Deserialize<T>(formatter.Deserialize(rems));
想的有点儿多~,先用下面方法转成json。
String json=Newtonsoft.Json.JsonConvert.SerializeObject(value);
然后把字符串json转为byte[]。之后把byte[]转为字符串,再用
Person p=Newtonsoft.Json.JsonConvert.DeserializeObject<Person>(json);
body = ms.ToArray();
反写回去,就可以了