Unity内置JsonUtility.FromJson解析List

 注意:

JsonUtility.FromJson 方法只能接受 json 对象,如果是 json 数组会提示错误 JSON must represent an object type

被转换的对象必须是可被序列化的,需要标记 [System.Serializable] 属性

 

写数据类

    public class VideoData
    {
        public List datas;
    }
    [Serializable]
    public class JsonVideoData
    {
        public int id;
        public int type;
        public string name;
    }

 调用

        public List jsonVideoDatas = new List();
        void ReadVideoJson()
        {
            string jsonStr = File.ReadAllText(videoPathDir + videoJsonName);
            //Debug.Log(jsonStr);
            jsonVideoDatas = JsonUtility.FromJson(jsonStr).datas;
        }

 Json数据,注意json的键和自定义的类的字段完全一致,否则读不到数据

{
  "datas": [
    {
      "id": 1,
      "type": 1,
      "name": "中国功夫.mp4"
    },
    {
      "id": 2,
      "type": 1,
      "name": "FuChouZhe.mp4"
    },
    {
      "id": 3,
      "type": 2,
      "name": "geminiman30fps.mp4"
    },
    {
      "id": 4,
      "type": 2,
      "name": "JindDianLuoYan3D.mp4"
    }
  ]
}

 

你可能感兴趣的:(Unity基础)