Serializing XNA Rectangle with Json.NET

后端 未结 3 1706
野趣味
野趣味 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:44

    I figured out a way to get Newtonsoft.Json (Json.Net) to play nice with XNA's Rectangle class. First, your rectangle should be a property of a class so you can give it a JsonConverter attribute:

    public class Sprite
    {
        [JsonConverter(typeof(MyRectangleConverter))]
        public Rectangle Rectangle;
    }
    
    public class MyRectangleConverter : JsonConverter
    {
        public override void WriteJson( JsonWriter writer, object value, JsonSerializer serializer )
        {
            var rectangle = (Rectangle)value;
    
            var x = rectangle.X;
            var y = rectangle.Y;
            var width = rectangle.Width;
            var height = rectangle.Height;
    
            var o = JObject.FromObject( new { x, y, width, height } );
    
            o.WriteTo( writer );
        }
    
        public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer )
        {
            var o = JObject.Load( reader );
    
            var x = GetTokenValue( o, "x" ) ?? 0;
            var y = GetTokenValue( o, "y" ) ?? 0;
            var width = GetTokenValue( o, "width" ) ?? 0;
            var height = GetTokenValue( o, "height" ) ?? 0;
    
            return new Rectangle( x, y, width, height );
        }
    
        public override bool CanConvert( Type objectType )
        {
            throw new NotImplementedException();
        }
    
        private static int? GetTokenValue( JObject o, string tokenName )
        {
            JToken t;
            return o.TryGetValue( tokenName, StringComparison.InvariantCultureIgnoreCase, out t ) ? (int)t : (int?)null;
        }
    }
    

    It could probably be improved so feedback is appreciated.

提交回复
热议问题