如何使用JSON.NET或DataContractJsonSerializer反序列化未类型化的对象 [英] How to deserialize an untyped object using JSON.NET or DataContractJsonSerializer

查看:91
本文介绍了如何使用JSON.NET或DataContractJsonSerializer反序列化未类型化的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在反序列化对象时重新创建它.通过重新实现Serialize和Deserialize方法,使我能够独立使用它们.由于我将序列化的对象存储在数据库中,因此我将无法访问该对象的类型(类). 问题是:有没有一种方法可以反序列化和对象而不具有对象的类型,仅是JSON字符串?从JSON字符串中获取类型的任何方法吗?

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?

以下是方法:

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

推荐答案

Json.Net具有TypeNameHandling枚举,可以在序列化程序设置中指定该枚举以执行您想要的操作(请参阅文档

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.

具体来说,尝试:

var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
var serialized = JsonConvert.SerializeObject(value, settings);
var deserialized = JsonConvert.DeserializeObject(value, settings);

当然,这要求所讨论的类型在序列化和反序列化应用程序中均可用.如果没有,Json.Net始终可以反序列化为JObjectIDictionary<string, object>,从而允许动态访问这些值.

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或DataContractJsonSerializer反序列化未类型化的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆