简体   繁体   English

如何使用JSON.NET或DataContractJsonSerializer反序列化未类型化的对象

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

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. 通过重新实现Serialize和Deserialize方法,使我能够独立使用它们。 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? 问题是:有没有一种方法可以反序列化和对象而不具有对象的类型,仅是JSON字符串? Any way to get it's type from the JSON string? 有什么方法可以从JSON字符串中获取类型吗?

Here are the methods: 方法如下:

DataContractJsonSerializer 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 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);
}

Json.Net has a TypeNameHandling enum which can be specified in serializer settings to do what you want (see documentation here ). Json.Net有一个TypeNameHandling枚举,可以在序列化程序设置中指定该枚举来执行您想要的操作(请参阅此处的文档)。 It sounds like you want TypeNameHandling.All. 听起来您想要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. 否则,Json.Net可以始终反序列化为JObjectIDictionary<string, object> ,从而允许动态访问值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM