This question was
closed Jul 25, 2018 at 03:48 PM by
UnityCoach for the following reason:
Lead to sufficient material was provided.
Question by
this_Jamal · Jul 25, 2018 at 11:39 AM ·
unity 5jsonserializable
Reading json file
how do I read?
Json:
{
"data":[[1.0, 1.5,2.0],[4.0, 4.5, 5.0]]
}
C#:
public class test : MonoBehaviour {
string path;
string jsonString;
void Start () {
path = Application.streamingAssetsPath + "/acadunity.json";
jsonString = File.ReadAllText(path);
Creature Lines = JsonUtility.FromJson<Creature>(jsonString);
print(Lines.data[0]);
}
}
[Serializable]
public class Creature{
public int[] data;
}
ERROR!!!!
Comment
I'm not sure this is the only problem, but your class data
field is of type int []
, and the data in the json file contains Vectors.
Answer by UnityCoach · Jul 25, 2018 at 12:03 PM
Try this :
[Serializable]
public class Creature
{
public Vector3 [] data;
}
I get:
(0.0, 0.0, 0.0)
json:
{
"lines":[[1,0.3544,0.0],[5.0,0.0,0.0]
]}
Did you try the opposite ? Serializing an object and look at the son file ?
No, is there another way to read? and I want to read the first number "1" can you tell me how?
json:
{
"number":[
{"x":439.0,"y":234.0,"z":342.0},{"x":1.0,"y":2.0,"z":3.0}
]
}
any idea? to get x or y or z.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO;
public class JsonTest : $$anonymous$$onoBehaviour
{
[Serializable]
public class TestClass
{
public Vector3 testValue = Vector3.right;
public Vector3 [] testValues = new Vector3[2] {Vector3.back, Vector3.up};
}
[SerializeField] TestClass testClass;
string GetPath ()
{
string path = Path.Combine(Application.dataPath, "test.json");
Debug.Log(path);
return path;
}
[Context$$anonymous$$enu ("Save")]
void Save ()
{
string jsonString = JsonUtility.ToJson(testClass, true);
StreamWriter writer = new StreamWriter (GetPath());
writer.Write(jsonString);
writer.Close();
}
[Context$$anonymous$$enu ("Load")]
void Load ()
{
StreamReader reader = new StreamReader (GetPath());
string jsonString = reader.ReadToEnd();
reader.Close();
JsonUtility.FromJsonOverwrite(jsonString, testClass);
}
}
/* Json Output
{
"testValue": {
"x": 1.0,
"y": 0.0,
"z": 0.0
},
"testValues": [
{
"x": 0.0,
"y": 0.0,
"z": -1.0
},
{
"x": 0.0,
"y": 1.0,
"z": 0.0
}
]
}
*/