C# JsonUtility.FromJson - can't convert my Json to c#
The second Debug.log(); show a value of 0, any ideas why the data isn't being correctly assigned?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Tests : MonoBehaviour
{
public string map = "test.json";
public static string LoadJsonMapFile(string path)
{
string filePath = path.Replace(".json", "");
TextAsset targetFile = Resources.Load(filePath) as TextAsset;
return targetFile.text;
}
void Start()
{
string jsonMapData = LoadJsonMapFile(map);
RootObject jsonMap = new RootObject();
jsonMap = JsonUtility.FromJson<RootObject>(jsonMapData);
Debug.Log("Name " + jsonMap.name + " : Desc " + jsonMap.description);
Debug.Log("Version " + jsonMap.map.version);
}
public class Map
{
public int version;
}
public class RootObject
{
public string name;
public string description;
public Map map = new Map();
}
}
My simplified Json file:
{
"name": "Shadow Realm",
"description": "A spooky Haloween inspired map",
"map": {
"version": 79
}
}
Answer by liortal · Jul 23, 2016 at 09:55 PM
According to the documentation for JsonUtility.FromJson (https://docs.unity3d.com/ScriptReference/JsonUtility.FromJson.html):
Internally, this method uses the Unity serializer; therefore the type you are creating must be supported by the serializer. It must be a plain class/struct marked with the Serializable attribute. Fields of the object must have types supported by the serializer.
You should decorate your Map class with the [Serializable] attribute.
Your answer
Follow this Question
Related Questions
How to code a simple C# timer? 2 Answers
How can I reset the score counter? 2 Answers
Object and first-person controller's collision not being registered 1 Answer
Console Debug / Print do not show 2 Answers
Destroy specific object with tag 2 Answers