Serializing XNA Rectangle with Json.NET

后端 未结 3 1687
野趣味
野趣味 2020-12-19 13:20

I\'m using Json.NET First look at this:

using System.Drawing;
string json = JsonConvert.SerializeObject(new Rectangle(-3,6,32,32), Formatting.Indented);
Con         


        
3条回答
  •  隐瞒了意图╮
    2020-12-19 13:31

    I've done some checking, this is the code that causes the exception:

        public static bool TryConvert(object initialValue, CultureInfo culture, Type targetType, out object convertedValue)
        {
          return MiscellaneousUtils.TryAction(delegate { return Convert(initialValue, culture, targetType); }, out convertedValue);
        }
    
    
    

    The actual call to the delegate that does the Convert work cannot find a convertor for this type. Investigating the cause for this, as the serializer is able to serialize and deserialize other types correctly.

    EDIT:

    This does not work, since the XNA Rectangle type is defined as:

        [Serializable]
        [TypeConverter(typeof(RectangleConverter))]
        public struct Rectangle : IEquatable
    

    Json.NET retrieves TypeConverter type, and calls this method on it:

      TypeConverter fromConverter = GetConverter(targetType);
    
      if (fromConverter != null && fromConverter.CanConvertFrom(initialType)) 
      {
           // deserialize
      }
    

    The RectangleConverter has a flag saying "supportsStringConvert = false", so attempting to convert a string into it fails.

    This is the reason that deserializing this specific object is failing.

    提交回复
    热议问题