原文内容来自:Read from and write to external .json files using JsonUtilities or LitJson
文件Unity 版本号5.3,使用时候Unity 版本号5.6
本文仅作分析,学习用途。
_2ReadJson_LitJson
----------------------------------------------------------------------------------------------原代码+注释
// Read JSON File and transform the string to objects
// using LitJson
using UnityEngine;
using System.Collections;
using System.IO;
using LitJson;
using System.Collections.Generic;
public class _2ReadJson_LitJson : MonoBehaviour {
void Start () {
/**
* 1. Fetch JSON-formatted string from text file
*/
// string jsonString = "{ \"name\": \"Fabi\", \"level\": \"4711\", \"tags\": [\"Beginner\",\"Fast\"] }";
string jsonString = File.ReadAllText (Application.dataPath + "/Resources/Json_basic.json");
//定义 一个字符串 jsonString
//读取 路径Application.dataPath + "/Resources/Json_basic.json" 的.json文件
/**
* 2. Transform JSON-formatted text into object
*/
//转换 JSON格式 ,使得 jsonString字符串变量 转换 为JSON格式
JsonData myObject = JsonMapper.ToObject (jsonString);
//定义 一个 string的list变量,名字为tagsList,并赋值
List<string> tagsList = new List<string> ();
//for循环,遍历每一个 JSON格式变量 myObject 里面"tags" 的数量
for (int i=0; i < myObject ["tags"].Count; i++) {
tagsList.Add(myObject["tags"][i].ToString());
//使得 每一个 JSON格式变量 myObject 里面"tags" 转换为 字符串 ,
//并且使得已经转换完毕的字符串 添加到tagsList 字符串List中
}
//遍历 每一个 在字符串List 的tagsList 的 tags,显示并且输出字符串
foreach (string tag in tagsList) {
Debug.Log ("Print List Item: " + tag); // logs Beginner, then Fast
}
}
}
----------------------------------------------------------------------------------------------代码图片
----------------------------------------------------------------------------------------------代码运行的结果
----------------------------------------------------------------------------------------------