I was trying to convert a list into json format.The jsonstring I am getting is always empty.Code below
[System.Serializable]
public class ListContainer
{
public List<PlayerHandler> SaveValues;
public ListContainer(List<PlayerHandler> _saveVal)
{
SaveValues = _saveVal;
}
}
public class Testing : MonoBehaviour
{
List<PlayerHandler> getAlldata;
var container = new ListContainer(getAlldata);
string jsonstring = JsonUtility.ToJson(container);
//the jsonstring is always empty
}
This question asked million times before. Unity serializer do not support arrays as root object as stated in the manual.
[Serializable]
class Container<T> {
public T[] array;
}
From the below code I once got the json string.So what is the difference I am passing the same list in the below code.
public struct ListContainer
{
public List<DataHandlers> SaveValues;
/// <summary>
/// Constructor
/// </summary>
/// <param name="_dataList">Data list value</param>
public ListContainer(List<DataHandlers> _dataList)
{
SaveValues = _dataList;
}
}
SaveValues.Clear();
SaveValues = UnityARHitTestExample.HittestInstance.Modelinfo;
ListContainer container = new ListContainer(SaveValues);
string jsonstring = JsonUtility.ToJson(container);
Debug.Log("Save JSON String = " + jsonstring);
Where Modelinfo
public List<DataHandlers> Modelinfo = new List<DataHandlers>();
[Serializable]
public class DataHandlers
{
public int modelid;
public Vector3 localposinmap;
public Quaternion localrotinmap;
public Vector3 sizeofobj;
public DataHandlers(int idmodel,Vector3 localpos, Quaternion localrot, Vector3 objsize)
{
this.modelid = idmodel;
this.localposinmap = localpos;
this.localrotinmap = localrot;
this.sizeofobj = objsize;
}
}
Your first example getAllData is null, I’m not sure what jsonUtility does with that to begin with. Beyond that, I usually use json.net for my json stuff.
In both the cases I am using a list.In one I got a json string and in another I dont get it.