How to serialize vector3 with JSON.net?
Hi,
I'm trying to serialize vector3 fields using JSON.net, however, it's also serializing normalized values and magnitudes, e.g.:
{
"x": -0.139040321,
"y": -0.0536295325,
"z": -0.250134617,
"normalized": {
"x": -0.47753495,
"y": -0.184191,
"z": -0.8590891,
"magnitude": 1.0,
"sqrMagnitude": 1.0
},
"magnitude": 0.2911626,
"sqrMagnitude": 0.0847756639
}
I know you can use attributes to specify which fields/properties should be included for serialization, but since I don't own this type that doesn't seem like a viable approach.
Is anyone using JSON.net to serialize just the xyx components of vector3? If so how?
Thank you
Answer by JerkyTreatz · May 01, 2017 at 04:17 PM
Not sure if the OP found a solution, but I was getting this same error. I decided to just create a Vector3Json object with just x, y, z
properties. When saving the objects, I would create this object from the Vector3 and serialize.
Answer by ModLunar · Feb 16, 2020 at 04:06 PM
In Unity 2020.1 Alpha, I managed to get Newtonsoft.Json through the Unity package manager. I customized its serialization by inheriting from DefaultContractResolver and creating a JsonConverter<float>.
The custom DefaultContractResolver makes the serialization work just like Unity's serializer.
The JsonConverter<float> gives us the power to decide how many decimal places ALL floats will serialize with.
I describe it and posted the code on the Unity forums.
Your answer
Follow this Question
Related Questions
JsonUtils.ToJson alters the object?? 0 Answers
Recursive JSON serialization / serialize list of custom serializable objects? 1 Answer
Exlcude fields from JsonUtility but still serialise them? 1 Answer
JsonUtility and Arrays - JSON must represent an object type. 0 Answers
Argument Exception: J SON must represent an object type. Serialization list of objects 0 Answers