- Home /
JsonUtility not working with Arrays
Hello,
I'm having a problem serializing an array into json. I am using Unity's JsonUtility and I thought they were supported since some people said it here. Anyways if it isn't supported how could I do it without, if it is, then why does this code not work?
// Test array that will be converted
string[] test = new string[] { "test", "Hello World"};
// Get the length of the array to convert
Debug.Log(test.Length);
// Convert array to json
string json = JsonUtility.ToJson(test);
// This returns {}
Debug.Log(json);
For some reason my output is
2
{}
Thanks!
I never used Unity's JsonUtility so i can't say anything for sure but as far as i know it requires the root object to be a class. So you can't directly serialize an array or a simple value. Try with a class around
Yup that was it! I just had to put the Array inside a class and it worked! Thanks a lot!
Answer by PandawanFr · Nov 28, 2016 at 05:55 AM
Thanks to @Bunny83, it works now!
All I had to do was put the array inside it's own custom class and then mark that class as [Serializable] and just use ToJson with that object instead.
Answer by ztougas · Nov 28, 2016 at 08:07 AM
This works...you need an Object to define the call for JSON.
using UnityEngine; using System.Collections;
public class MaterialController : MonoBehaviour {
// Use this for initialization
void Start () {
//store the retrieved JSON object to a string
string json = "";
TestObject testobj = new TestObject();
testobj.test = "My test string";
json = JsonUtility.ToJson(testobj);
Debug.Log (json);
}
//*************************************************
// JSON Object structure for JSON Decoding.
//*************************************************
[System.Serializable] public struct TestObject {
public string test;
}
}
And this is what my log shows:
{"test":"$$anonymous$$y test string"} UnityEngine.Debug:Log(Object) $$anonymous$$aterialController:Start() (at Assets/_Scripts/$$anonymous$$aterialController.cs:19)
Your answer
Follow this Question
Related Questions
How to create array of GamwObject 0 Answers
How to serialize an array with custom properties in Java script? 1 Answer
Serialize large array of class 0 Answers
Serialize unity classes 0 Answers
Help using LitJson 1 Answer