How to deserialize an untyped object using JSON.NET or DataContractJsonSerializer

微笑、不失礼 提交于 2020-01-07 01:21:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!