0

Json data form of my project is like this.

[
    {
        "UnitName" : "A" ,
        "Level" : "1" ,
        "HitPoint" : "450" ,
        "Damage" : "8" ,
        "Experience" : "100" 
    },
    {
        "UnitName" : "A" ,
        "Level" : "2" ,
        "HitPoint" : "540" ,
        "Damage" : "11" ,
        "Experience" : "150" 
    },
    ....
]

I tried to read this using JsonUtility. This is my reading Json code.

public void Load()
{   
        string jsonString = File.ReadAllText(Application.dataPath + "/Database/SpiritDataA.json");   
        CharacterData data = JsonUtility.FromJson<CharacterData>(jsonString);
        Debug.Log(data);
}

I was test it, and get this error.

ArgumentException: JSON must represent an object type.

I tried by other method that using in array.

[Serializable]
public class Wrapper<T>
{
    public T[] items;
}

public class JsonHelper
{
    public void Load()
    {
        string jsonString = File.ReadAllText(Application.dataPath + "/Database/SpiritData.json");
        CharacterData data = JsonUtility.FromJson<CharacterData>(jsonString);

        Debug.Log(data);
    }

    public CharacterData[] FromJson(string s)
    {
        return JsonUtility.FromJson<Wrapper<CharacterData>>(s).items;
    }
}

I get same error.

As a result of a Google search, I think that this file structure is a bit different from other common things. but I want to read the file, preserving the existing format if possible.

How can i do?

WhiteBear
  • 11
  • 3
  • for which platform you are building, check respective return string [Application.dataPath](https://docs.unity3d.com/ScriptReference/Application-dataPath.html) – eagle Dec 11 '17 at 02:52
  • Can you add what is your CharacterData code is? We can have a look at it. – killer_mech Dec 11 '17 at 05:25
  • 2
    Your object is an array and JsonUtility does not support array object, hence the error. https://stackoverflow.com/questions/36239705/serialize-and-deserialize-json-and-json-array-in-unity/36244111 – Everts Dec 11 '17 at 06:45
  • I would recommend using LitJson https://lbv.github.io/litjson/ – Fiffe Dec 11 '17 at 07:00
  • @Everts is right. This is Json array. See duplicate for how to do so. – Programmer Dec 11 '17 at 09:41
  • Everybody Thank you! I read and enter rink all. I solved it with various help. I saw feedback that my question is dulicate question. Should I erase this? – WhiteBear Dec 12 '17 at 04:26

0 Answers0