Hello all
I’m having trouble getting values from jsons. I made a “test.json” containing only one string, it seems that i can’t load it. It doesn’t give me any errors, but what i end up loading is an empty string instead of the actual value.
main.cs
Dialogue dialogue = null;
private void ReturnDialogueFromJson()
{
string path = "saves/dial/test";
TextAsset jsonFile = Resources.Load(path) as TextAsset;
Debug.Log("json file name: " + jsonFile.name); //this DOES return "test"
dialogue = JsonUtility.FromJson<Dialogue>(jsonFile.text);
}
public void startDialogue() // i call this from a trigger
{
ReturnDialogueFromJson();
Debug.Log("Start conversation with " + dialogue.Name); //!!returns only "Start conversation with "
}
Dialoge.cs
[System.Serializable]
public class Dialogue
{
public string Name { get; set; }
}
test.json
{
"Name" : "Walter"
}
I can succesfully print the TextAsset file name (and changing the path results in an error), so the TextAsset should get loaded correctly…
Well, just installing the newtonsoft json library and not changing anything about your code of course would not do anything. You’re still using Unity’s JsonUtility in your code. The Newtonsoft Json.NET library comes with it’s own classes. You probably want to use
instead. Please have a look at the documentation of the library you’re using.
ps: Unity’s JsonUtility would work as well, but not with your Dialogue class as Unity only serializes fields and not properties. You made your “Name” a property.
pps: You named your class “Dialogue” but your file “Dialoge.cs”. It may just be a typo here in the forum, but if not it should be unified ^^.
Thanks! Did not know that. Changed it to a field, and now it works.
Also yeah i included the link to Newtonsoft lib just in case, but for now i’d rather work with Unity’s libraries untill i better understand JSON operations. Unless there is a reason to always use Newtonsoft libs (way more efficient)?
Thanks again!
In general I highly suggest staying away from Unity’s JSON “tiny lite” package. It’s really not very capable at all and will silently fail on very common data structures, such as Dictionaries and Hashes and ALL properties.
Instead grab Newtonsoft JSON .NET off the asset store for free, or else install it from the Unity Package Manager (Window → Package Manager).