I'm trying to JSonSerialier in Unity which I used in a stand alone Console project. However this fails on Unity.
Example:
public class MyClass
{
public int level {get; set;}
public float timeElapsed {get; set;}
public string playerName {get; set;}
}
Then in some function of the code I do this:
MyClass myObject = new MyClass();
myObject.level = 1;
myObject.timeElapsed = 47.5f;
myObject.playerName = "Dr Charles Francis";
Console.WriteLine(JsonSerializer.Serialize(myObject));
This works perfectly fine in a code that I run using "dotnet run" on Windows.
However when I use this in one of the Unity Scripts, I get the following error:
'JsonSerializer' is inaccessible due to its protection level
So how can I use JsonSerializer in Unity?
The JsonSerializer seems not to work properly with Unity. I have switched to using Newtonsoft.Json instead.
What you can do to achieve the desired result is:
Define your class as you did already:
public class MyClass
{
public int level {get; set;}
public float timeElapsed {get; set;}
public string playerName {get; set;}
}
Add the import to your file/class where you are using the JSON:
using Newtonsoft.Json.Linq;
And inside your processing class use the following method:
private void SendJson(MyClass _event)
{
string json = Newtonsoft.Json.JsonConvert.SerializeObject(_event);
byte[] jsonBytes = Encoding.UTF8.GetBytes(json);
}
The json string or jsonBytes array can be used to e.g. send it to a server.
I hope this helps - please let me know if I can be of any further help.
In addition to the Newtonsoft JSON library already suggest in the other answer, for simple things there's also the Unity-native JsonUtility.ToJson:
string jsonString = JsonUtility.ToJson(someClass);
You do get floating point accuracy oddities though, e.g. 0.7f may turn into 0.699999988079071 when serialized, and Newtonsoft fixes that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With