user97975
user97975

Reputation: 27

3d array data in json file, I want to read the content in C# unity

jsonfile content: {"values": [[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]], [[10.0, 11.0, 12.0], [13.0, 14.0, 15.0], [16.0, 17.0, 18.0]], [[19.0, 20.0, 21.0], [22.0, 23.0, 24.0], [25.0, 26.0, 27.0]]]} I want to read the content of this file element wise.then I want to create mesh for this in unity.

I am using this code:

public class JsonDataread : MonoBehaviour
{
    [System.Serializable]
    public class DataObject
    {
        public float[][][] values; 
    }

    DataObject dataObject = new DataObject();

    void Start()
    {
          string jsonString  "Assets\\data\\array3d.json";

  string jsonString = File.ReadAllText(jsonFilePath);  // this show the content in string format. 

        dataObject = JsonUtility.FromJson<DataObject>(jsonString);
 
}

but when I try to get dataObject.values shows Null. i want each elements access.

Upvotes: -2

Views: 82

Answers (1)

derHugo
derHugo

Reputation: 90813

JsonUtility and Unity serializer in general does not support complex collections

Note: Unity doesn’t support serialization of multilevel types (multidimensional arrays, jagged arrays, dictionaries, and nested container types).

The two mentioned options won't help you except the content of the json is allowed to have a slightly different format of course.

⇒ use e.g. Newtonsoft Json.NET instead. It doesn't directly show up in the PackageManager but you can install by name

com.unity.nuget.newtonsoft-json

and then use

using Newtonsoft.Json;

...

var json = "{\"values\": [[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]], [[10.0, 11.0, 12.0], [13.0, 14.0, 15.0], [16.0, 17.0, 18.0]], [[19.0, 20.0, 21.0], [22.0, 23.0, 24.0], [25.0, 26.0, 27.0]]]}";
        
var data = JsonConvert.DeserializeObject<DataObject>(json);
Debug.Log(data[0][0][0]);

Upvotes: 0

Related Questions