0

Want to convert a object to a json string and back.

My object:

[Serializable]
public class Save
{
    public Levels PlayerLvl { get; set; }
    public int Kills { get; set; }
}

function in code:

testfunction(Save savedata) {
    //(int)savedata.PlayerLvl equals 1
    //savedata.Kills equals 5
    string json = JsonUtility.ToJson(savedata);
    debug.log(json) // json equals "{}"
}

The same happens when I get a json string and want to convert it back:

testFunction(string jsonstring) {
    //jsonstring is a valid json string that equals Save object
    Save savedata = JsonUtility.FromJson<Save>(jsonstring);
    // savedate equals a new Save object without content
}

whats wrong here?


Edit:

Json that I get:

{
    "Kills": 5,
    "PlayerLvl": 1
}

Levels enum:

public enum Levels {
    Level1 = 1,
    Level2 = 2
}
4
  • can you show the json example and the Levels class Commented Mar 12, 2020 at 10:16
  • 5
    afaik JsonUtility doesn't support properties, either use fields or a different library such as Json.NET Commented Mar 12, 2020 at 10:27
  • try to add [Serializable]also for public enum Levels Commented Mar 12, 2020 at 10:28
  • remove all the get;set; as JsonUtility does not support properties. Commented Mar 12, 2020 at 10:30

1 Answer 1

2

See from Manual: JSON Serialization

Supported types

The JSON Serializer API supports any MonoBehaviour subclass, ScriptableObject subclass, or plain class or struct with the [Serializable] attribute. When you pass in an object to the standard Unity serializer for processing, the same rules and limitations apply as they do in the Inspector: Unity serializes fields only; and types like Dictionary<> are not supported.

Unity does not support passing other types directly to the API, such as primitive types or arrays. If you need to convert those, wrap them in a class or struct of some sort.

So you want to remove all {get; set;} in order to use fields not properties

[Serializable]
public class Save
{
    public Levels PlayerLvl;
    public int Kills;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.