<tfoot id='FDhEi'></tfoot>
  • <i id='FDhEi'><tr id='FDhEi'><dt id='FDhEi'><q id='FDhEi'><span id='FDhEi'><b id='FDhEi'><form id='FDhEi'><ins id='FDhEi'></ins><ul id='FDhEi'></ul><sub id='FDhEi'></sub></form><legend id='FDhEi'></legend><bdo id='FDhEi'><pre id='FDhEi'><center id='FDhEi'></center></pre></bdo></b><th id='FDhEi'></th></span></q></dt></tr></i><div id='FDhEi'><tfoot id='FDhEi'></tfoot><dl id='FDhEi'><fieldset id='FDhEi'></fieldset></dl></div>
    <legend id='FDhEi'><style id='FDhEi'><dir id='FDhEi'><q id='FDhEi'></q></dir></style></legend>

    • <bdo id='FDhEi'></bdo><ul id='FDhEi'></ul>

      1. <small id='FDhEi'></small><noframes id='FDhEi'>

        在 JsonConverter 中递归调用 JsonSerializer

        Recursively call JsonSerializer in a JsonConverter(在 JsonConverter 中递归调用 JsonSerializer)
          <bdo id='jDyKk'></bdo><ul id='jDyKk'></ul>
              <tbody id='jDyKk'></tbody>
            <legend id='jDyKk'><style id='jDyKk'><dir id='jDyKk'><q id='jDyKk'></q></dir></style></legend>

          • <tfoot id='jDyKk'></tfoot>
            <i id='jDyKk'><tr id='jDyKk'><dt id='jDyKk'><q id='jDyKk'><span id='jDyKk'><b id='jDyKk'><form id='jDyKk'><ins id='jDyKk'></ins><ul id='jDyKk'></ul><sub id='jDyKk'></sub></form><legend id='jDyKk'></legend><bdo id='jDyKk'><pre id='jDyKk'><center id='jDyKk'></center></pre></bdo></b><th id='jDyKk'></th></span></q></dt></tr></i><div id='jDyKk'><tfoot id='jDyKk'></tfoot><dl id='jDyKk'><fieldset id='jDyKk'></fieldset></dl></div>

                  <small id='jDyKk'></small><noframes id='jDyKk'>

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

                  问题描述

                  限时送ChatGPT账号..

                  我正在编写一个 JsonConverter 来执行一些我需要在读/写时完成的转换任务.特别是,我采用了现有的序列化行为,并在写入/读取时添加了一些附加属性.

                  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.

                  JsonConverter 中,我想利用传递的 JsonSerializer 实例来执行大部分转换功能.但是,当我这样做时,我最终会进入一个递归循环,其中序列化程序调用我的转换器,然后调用序列化程序,然后调用转换器等等.

                  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.

                  我见过人们使用 JsonConvert.SerializeObject,从序列化器实例 except this 传入所有转换器.但是,这对我不起作用,因为它绕过了我在序列化程序上完成的所有其他自定义,例如自定义合同解析器和 DateTime 处理.

                  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.

                  有没有办法:

                  1. 使用传递给我的序列化程序实例,但以某种方式排除我的转换器,或者
                  2. 克隆传递给我的序列化程序(无需手动构建一个新序列化程序并逐个属性地复制它)并删除我的转换器?

                  推荐答案

                  这是一个很常见的问题.使用JsonConvert.SerializeObject"不是一个坏主意.但是,在某些情况下(通常是集合)可以使用的一个技巧是在写入时强制转换为接口,并在读取时反序列化为简单的派生.

                  This is a very common problem. Using "JsonConvert.SerializeObject" isn't a bad idea. However, one trick that can be used in some circumstances (typically collections) is to cast to the interface when writing and deserialize to a simple derivative when reading.

                  下面是一个简单的转换器,它处理可能被序列化为一组 KVP 而不是看起来像一个对象的字典(在这里显示我的年龄 :))

                  Below is a simple converter that deals with dictionaries that might have been serialized as a set of KVPs rather than looking like an object (showing my age here :) )

                  注意WriteJson"转换为 IDictionary

                  K,V> 和ReadJson"使用DummyDictionary".您最终得到了正确的结果,但使用了传递的序列化程序而不会导致递归.

                  Note "WriteJson" casts to IDictionary< K,V> and "ReadJson" uses "DummyDictionary". You end up with the right thing but uses the passed serializer without causing recursion.

                  /// <summary>
                  /// Converts a <see cref="KeyValuePair{TKey,TValue}"/> to and from JSON.
                  /// </summary>
                  public class DictionaryAsKVPConverter<TKey, TValue> : JsonConverter
                  {
                      /// <summary>
                      /// Determines whether this instance can convert the specified object type.
                      /// </summary>
                      /// <param name="objectType">Type of the object.</param>
                      /// <returns>
                      ///     <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
                      /// </returns>
                      public override bool CanConvert(Type objectType)
                      {
                          if (!objectType.IsValueType && objectType.IsGenericType)
                              return (objectType.GetGenericTypeDefinition() == typeof(Dictionary<,>));
                  
                          return false;
                      }
                  
                      /// <summary>
                      /// Writes the JSON representation of the object.
                      /// </summary>
                      /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
                      /// <param name="value">The value.</param>
                      /// <param name="serializer">The calling serializer.</param>
                      public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
                      {
                          var dictionary = value as IDictionary<TKey, TValue>;
                          serializer.Serialize(writer, dictionary);
                      }
                  
                      /// <summary>
                      /// Reads the JSON representation of the object.
                      /// </summary>
                      /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
                      /// <param name="objectType">Type of the object.</param>
                      /// <param name="existingValue">The existing value of object being read.</param>
                      /// <param name="serializer">The calling serializer.</param>
                      /// <returns>The object value.</returns>
                      public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
                      {
                          Dictionary<TKey, TValue> dictionary;
                  
                          if (reader.TokenType == JsonToken.StartArray)
                          {
                              dictionary = new Dictionary<TKey, TValue>();
                              reader.Read();
                              while (reader.TokenType == JsonToken.StartObject)
                              {
                                  var kvp = serializer.Deserialize<KeyValuePair<TKey, TValue>>(reader);
                                  dictionary[kvp.Key] = kvp.Value;
                                  reader.Read();
                              }
                          }
                          else if (reader.TokenType == JsonToken.StartObject)
                              // Use DummyDictionary to fool JsonSerializer into not using this converter recursively
                              dictionary = serializer.Deserialize<DummyDictionary>(reader);
                          else
                              dictionary = new Dictionary<TKey, TValue>();
                  
                          return dictionary;
                      }
                  
                      /// <summary>
                      /// Dummy to fool JsonSerializer into not using this converter recursively
                      /// </summary>
                      private class DummyDictionary : Dictionary<TKey, TValue> { }
                  }
                  

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

                  本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

                  相关文档推荐

                  Force JsonConvert.SerializeXmlNode to serialize node value as an Integer or a Boolean(强制 JsonConvert.SerializeXmlNode 将节点值序列化为整数或布尔值)
                  Using JSON to Serialize/Deserialize TimeSpan(使用 JSON 序列化/反序列化 TimeSpan)
                  Could not determine JSON object type for type quot;Classquot;(无法确定类型“Class的 JSON 对象类型.)
                  How to deserialize a JSONP response (preferably with JsonTextReader and not a string)?(如何反序列化 JSONP 响应(最好使用 JsonTextReader 而不是字符串)?)
                  how to de-serialize JSON data in which Timestamp it-self contains fields?(如何反序列化时间戳本身包含字段的JSON数据?)
                  JSON.Net custom contract serialization and Collections(JSON.Net 自定义合约序列化和集合)
                  <legend id='EHdT9'><style id='EHdT9'><dir id='EHdT9'><q id='EHdT9'></q></dir></style></legend>

                    <i id='EHdT9'><tr id='EHdT9'><dt id='EHdT9'><q id='EHdT9'><span id='EHdT9'><b id='EHdT9'><form id='EHdT9'><ins id='EHdT9'></ins><ul id='EHdT9'></ul><sub id='EHdT9'></sub></form><legend id='EHdT9'></legend><bdo id='EHdT9'><pre id='EHdT9'><center id='EHdT9'></center></pre></bdo></b><th id='EHdT9'></th></span></q></dt></tr></i><div id='EHdT9'><tfoot id='EHdT9'></tfoot><dl id='EHdT9'><fieldset id='EHdT9'></fieldset></dl></div>
                      <tbody id='EHdT9'></tbody>

                      <small id='EHdT9'></small><noframes id='EHdT9'>

                      <tfoot id='EHdT9'></tfoot>

                            <bdo id='EHdT9'></bdo><ul id='EHdT9'></ul>