使用Json.NET序列化XNA矩形 [英] Serializing XNA Rectangle with Json.NET

查看:44
本文介绍了使用Json.NET序列化XNA矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 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);

一切正常.控制台输出为:"3、6、32、32"

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

但是当我想对 XNA矩形,出现错误. (只是用使用Microsoft.Xna.Framework;"代替了旧的使用方法.)

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

控制台输出为:"{X:-3 Y:6宽度:32高度:32}"

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

抛出的错误是:将值" {X:-3 Y:6 Width:32 Height:32}转换为Microsoft.Xna.Framework.Rectangle'时出错."

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

  1. 为什么会这样?

  1. Why is this happening?

出了什么问题,我该如何解决?

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

推荐答案

我已经做了一些检查,这是导致异常的代码:

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.

这不起作用,因为XNA矩形类型定义为:

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

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

Json.NET检索TypeConverter类型,并在其上调用此方法:

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

  TypeConverter fromConverter = GetConverter(targetType);

  if (fromConverter != null && fromConverter.CanConvertFrom(initialType)) 
  {
       // deserialize
  }

RectangleConverter具有一个标记为"supportsStringConvert = false"的标记,因此尝试将字符串转换为它失败.

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.

这篇关于使用Json.NET序列化XNA矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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