递归调用JsonSerializer在JsonConverter [英] Recursively call JsonSerializer in a JsonConverter

查看:311
本文介绍了递归调用JsonSerializer在JsonConverter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个 JsonConverter 来执行我需要完成的读/写一些转换任务。特别是,我是在现有的序列化行为,并写上套结了一些额外的属性/在读读取这些附加属性。

JsonConverter ,我想利用通过 JsonSerializer 实例来执行大多数转换功能。然而,当我这样做,我最终在一个递归循环,串行器调用到我的转换器,它调用到它调用到转换器等串行。

我见过的人做的事情,如使用 JsonConvert.SerializeObject ,传递从串行器实例中的所有转换器的除了。不过,这不是我的工作,因为它绕过所有其他自定义我已经做了我的序列化,如定制合同解析器和的DateTime 处理。

有没有一种方法,我可以:

  1. 使用传给我的序列化实例,但不知何故不包括我转换器,或
  2. 克隆传递给我的串行(无需手动构建一个新的,复制它由property属性),并删除我的转换器?
解决方案

我终于实现了使用Automapper创建的(MEH)解决方案 JsonSerializerSettings 根据 JsonSerializer ,并使用 JsonConvert 与新对象。这是一个贫穷的解决方案。

I'm writing a JsonConverter to perform some conversion tasks I need accomplished on read/write. In particular, I'm taking the existing serialization behavior and tacking on some additional properties on write / reading those additional properties on read.

Inside the JsonConverter, I'd like to make use of the passed JsonSerializer instance to perform the majority of the conversion functionality. However, when I do this, I end up in a recursive loop where the serializer calls into my converter which calls into the serializer which calls into the converter and etc.

I've seen people do things such as use JsonConvert.SerializeObject, passing in all the converters from the serializer instance except this. However, that won't work for me because it bypasses all of the other customization I've done on my serializer, such as custom contract resolver and DateTime handling.

Is there a way I can either:

  1. Use the serializer instance passed to me, but somehow exclude my converter, or
  2. Clone the serializer passed to me (without manually constructing a new one and copying it property by property) and remove my converter?

解决方案

I ended up doing the (meh) solution of using Automapper to create a JsonSerializerSettings based on the JsonSerializer, and using JsonConvert with that new object. This is a poor solution.

这篇关于递归调用JsonSerializer在JsonConverter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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