Json Utilities returns empty object (javascript)

For some reason, JsonUtility.ToJson() is returning " { } " every time no matter what I pass it.

tested not working example:

var foo:String = "bar";

this always returns “{ }”.
any idea why this is happening?

I’m not sure about the javascript version.

But in c# and a few other languages you need to tag the object in question with an attribute of some kind. Stating that it is allowed to be serialized. For example in c# above the object in question you would type [Serializable]. This allows the compiler to know that this object is intended to be serialized. Otherwise you would get an error or an empty object.

Json should run even better in javascript in theory.

I searched here, but didn’t see anything about javascript.

C# Note: to others, get set operator properties will not be serialized, Remove the get set and just leave it as a field. Otherwise you will only get a empty object ‘{}’.

It appears that ToJson can’t even convert native variables into a json format. I had the same problem with a list of strings and then realized that string, integer or boolean does not matter ToJson will return {} an empty json object.

So what it actually ask for is, in every case, a [Serializable] object. And your variable as a public variable in it.

class Text
    public string  foo = "bar";

class Main
    Text t = new Text();

    string json = JsonUtility.ToJson(t);


will result in { “foo” : “bar” }