How to give a new json key when using JSON Serialization.
[Serializable]
public class MyClass {
public int level;
public float timeElapsed;
public string playerName;
}
As the example, when call:
string json = JsonUtility.ToJson(myObject);
The result is:
{“level”:1,“timeElapsed”:47.5,“playerName”:“Dr Charles Francis”}
I wonder how can I change (and use) the key without change the properties name in class.
For example, the result is:
{“new_level”:1,“new_timeElapsed”:47.5,“new_playerName”:“Dr Charles Francis”}
Thank you!
I’m willing to bet unity didn’t include some method for doing that.
UnityEngine.Serialization.FormerlySerializedAsAttribute probably works though. Haven’t tested it. This would allow you to change the name of properties in your serializable class.
Otherwise, you may want to use some other json serializer that supports this.
Thank you very much.
I will check it.
Currently I’m working with an old server project, they use “params” as key. It’s not allow in Unity to have params as a properites name
So I just tested ‘FormerlySerializedAs’, and unfortunately it is not supported. Otherwise I would have said flag the ‘params’ property as FormerlySerializedAs(“params”), and then name it whatever you want.
But alas, they didn’t include it.
Despite unity specifically making their json serialization work a lot like their regular serialization (minus the unity object references of course). Maybe issue a request/bug??? It’d definitely be a nice addition to their JsonUtility.
I do know Json.Net supports an attribute for naming the json serialized property name, vs the class property name. Json.NET - Newtonsoft
I haven’t used it in unity as of yet (it’s primarily a .net library), I’m willing to bet it has issues with AOT, which is probably why such ports of it like this exist:
oof, 25 bucks…
I’d suggest giving vanilla json.net a try if you don’t need iOS/AOT support.
Otherwise, you could go about writing your own parser with your own attributes. I’m actually in the process of writing my own, but it’s not done, and is on the back burner right now because I don’t need it for our current project (I’m writing my own parser to support unity object serialization… I have a custom way of dealing with unity prefabs for save games, I currently use binary serialization for it though).
It’s intended to be very lightweight to parse. Note that link there, at the bottom, has links to multiple json libraries for different languages. They have a decent number of them for C#… check em’ out.
I just came across this same issue, seems no change?- it’s a real shame not to support FormerlySerializedAs.
I guess manual string replacements are only option