问题
I'm trying to recreate an object when deserializing it. By reimplementing the Serialize and Deserialize methods so that I'll be able to use them independently. Since I'll be storing the serialized object in the database, I won't be able to access the object's type (class). The problem is: is there a way to deserialize and object without having the object's type, only it's JSON string? Any way to get it's type from the JSON string?
Here are the methods:
DataContractJsonSerializer
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);
}
JSON.NET
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);
}
回答1:
Json.Net has a TypeNameHandling enum which can be specified in serializer settings to do what you want (see documentation here). It sounds like you want TypeNameHandling.All.
Specifically, try:
var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
var serialized = JsonConvert.SerializeObject(value, settings);
var deserialized = JsonConvert.DeserializeObject(value, settings);
Of course, this requires that the type in question be available in both the serializing and deserializing application. If not, Json.Net can always deserialize to a JObject
or IDictionary<string, object>
, allowing the values to be accessed dynamically.
来源:https://stackoverflow.com/questions/21470697/how-to-deserialize-an-untyped-object-using-json-net-or-datacontractjsonserialize