Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity: 'JsonSerializer' is inaccessible due to its protection level

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?

like image 321
aarelovich Avatar asked Oct 27 '25 22:10

aarelovich


2 Answers

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.

like image 58
M. Schröder Avatar answered Oct 29 '25 13:10

M. Schröder


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.

like image 38
Philipp Lenssen Avatar answered Oct 29 '25 13:10

Philipp Lenssen