Example of JsonConverter?

Oct 21, 2010 at 3:39 AM
Edited Oct 21, 2010 at 5:26 AM

I'm serializing some stuff in Unity3D, where Vector3 is automatically serialized by Json.NET (awesome!). However, it has some properties in it that store unecessary info like the normalized Vector3, the magnitude, etc. which I want to omit (but Json.NET includes them). How do I do that?

Here's an example of the output (the property is called position, which is a Vector3):

 

"Position": {             
"x": 69.54044,              
"y": 55.9183578,              
"z": 106.146866,             
 "normalized": {               
 "x": 0.5014747,               
 "y": 0.4032422,               
 "z": 0.7654534,                
 "magnitude": 1.0,                
 "sqrMagnitude": 1.0              
},             
"magnitude": 138.67189,              
"sqrMagnitude": 19229.8926

 

I only want the first x, y, z, not the other entries. Obviously Vector3 is an inbuilt struct, so I can't decorate it with JsonProperty and other attributes to do this.

Oct 23, 2010 at 1:39 PM
Edited Oct 23, 2010 at 1:50 PM

To half answer my own question:

using System;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using UnityEngine;

public class Vector3Converter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        if (value == null) return;

        Vector3 v = (Vector3)value;

        if (v == new Vector3())
        {
            writer.WriteNull();
            return;
        }

        writer.WriteStartObject();

        writer.WritePropertyName("x");
        serializer.Serialize(writer, v.x);

        writer.WritePropertyName("y");
        serializer.Serialize(writer, v.y);

        writer.WritePropertyName("z");
        serializer.Serialize(writer, v.z);
        
        writer.WriteEndObject();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.None) return null;

        reader.Read(); // Property X        
        reader.Read(); // Value X
        var x = (Single)serializer.Deserialize(reader, typeof(Single));
        
        reader.Read(); // Property Y
        reader.Read(); // Value Y
        var y = (Single)serializer.Deserialize(reader, typeof(Single));
        
        reader.Read(); // Property Z
        reader.Read(); // Value Z
        var z = (Single)serializer.Deserialize(reader, typeof(Single));

        reader.Read();

        return new Vector3(x, y, z);
    }

    public override bool CanConvert(Type objectType)
    {
        return (objectType.Equals(typeof(Vector3)));
    }
}

All I need to know now is how to tell it what's a default value so it can ignore it.