Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.NET serialization trouble

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.

like image 203
Alex Shkor Avatar asked Mar 17 '12 14:03

Alex Shkor


People also ask

How do you handle JSON deserialization error?

To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal . NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object.

What does JSON serialization mean?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).

Does .NET support JSON?

Text. Json namespace provides functionality for serializing to and deserializing from JavaScript Object Notation (JSON).

What is a JSON serialization exception?

The exception thrown when an error occurs during JSON serialization or deserialization.


1 Answers

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())
like image 66
svick Avatar answered Jan 03 '23 13:01

svick