Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
721 views
in Technique[技术] by (71.8m points)

c# - Serializing XNA Rectangle with Json.NET

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

using System.Drawing;
string json = JsonConvert.SerializeObject(new Rectangle(-3,6,32,32), Formatting.Indented);
Console.WriteLine(json);
Rectangle deserializedRectangle = JsonConvert.DeserializeObject<Rectangle>(json);

Everything works as expected. The console output is: "3, 6, 32, 32"

But when I want to do the same thing with the XNA Rectangle, I get an error. (just replaced the old using with this "using Microsoft.Xna.Framework;")

The console output is: "{X:-3 Y:6 Width:32 Height:32}"

and the error it throws is: "Error converting value "{X:-3 Y:6 Width:32 Height:32}" to type 'Microsoft.Xna.Framework.Rectangle'."

  1. Why is this happening?

  2. Whats going wrong, and how do I fix this??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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<object>(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<Rectangle>

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...