11

I have a class with property type of Point ( struct in .NET Framework). I use JsonConvert from Newton.Json to serialize it to JSON. But result is

 "Point" : "100,100" 

Instead of

 "Point" : { X: "100", Y: "100"}

When I replace JsonConvert with standard JavascriptSerializer, all works fine.

But I want to use JsonConverter from JSON.Net, because it's much faster.

2
  • yes, but I want to use JsonConverter from Json.Net, becouse it much faster. Commented Mar 17, 2012 at 14:57
  • Do you mean System.Drawing.Point, System.Windows.Point, or some other type? Commented Mar 17, 2012 at 15:29

1 Answer 1

11

That's because Point has defined its own TypeConverter and JSON.NET uses it to do the serialization. I'm not sure whether there is a clean way to turn this behavior off, but you can certainly create your own JsonConverter that behaves the way you want:

class PointConverter : JsonConverter
{
    public override void WriteJson(
        JsonWriter writer, object value, JsonSerializer serializer)
    {
        var point = (Point)value;

        serializer.Serialize(
            writer, new JObject { { "X", point.X }, { "Y", point.Y } });
    }

    public override object ReadJson(
        JsonReader reader, Type objectType, object existingValue,
        JsonSerializer serializer)
    {
        var jObject = serializer.Deserialize<JObject>(reader);

        return new Point((int)jObject["X"], (int)jObject["Y"]);
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Point);
    }
}

You can then use it like this:

JsonConvert.SerializeObject(
    new { Point = new Point(15, 12) },
    new PointConverter())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.