我正在尝试在反序列化时重新创建一个对象。通过重新实现Serialize和Deserialize方法,以便我能够独立使用它们。由于我将序列化对象存储在数据库中,因此我将无法访问对象的类型(类)。 问题是:有没有一种方法来反序列化和对象而没有对象的类型,只有它的JSON字符串?有什么方法可以从JSON字符串中获取它的类型吗?
以下是方法:
public string Serialize(object aoObject)
{
MemoryStream stream = new MemoryStream();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(aoObject.GetType());
serializer.WriteObject(stream, aoObject);
return Encoding.Default.GetString(stream.ToArray());
}
public object Deserialize(string asObject)
{
MemoryStream stream = new MemoryStream(Encoding.Default.GetBytes(asObject));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(["the type of the object"]));
return serializer.ReadObject(stream);
}
public string Serialize(object aoObject)
{
DefaultContractResolver dcr = new DefaultContractResolver();
dcr.DefaultMembersSearchFlags |= System.Reflection.BindingFlags.NonPublic;
JsonSerializerSettings jss = new JsonSerializerSettings();
jss.TypeNameHandling = TypeNameHandling.All;
jss.ContractResolver = dcr;
string asObject = JsonConvert.SerializeObject(loObject, jss);
}
public object Deserialize(string asObject)
{
["type of the object"] fake2 = JsonConvert.DeserializeObject(asObject);
}
答案 0 :(得分:0)
Json.Net有一个TypeNameHandling枚举,可以在序列化程序设置中指定它来执行您想要的操作(请参阅文档here)。听起来你想要TypeNameHandling.All。
具体来说,试试:
var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
var serialized = JsonConvert.SerializeObject(value, settings);
var deserialized = JsonConvert.DeserializeObject(value, settings);
当然,这要求序列化和反序列化应用程序中都提供有问题的类型。如果没有,Json.Net总是可以反序列化为JObject
或IDictionary<string, object>
,允许动态访问这些值。