Unity Android端解析Json文件

Json文件格式:

[
	{
   	 "triggerGameObject": "Cube",
     "gameObjectNum": "1",
	  "isRight":="True"
	},
	{
  	  "triggerGameObject": "Sphere",
 	   "gameObjectNum": "2",
	  "isRight":="false"
	}
]

将Json文件命名为:Data.json,(注意*保存时格式选择ANSI),将文件存放在Unity工程的StreamingAssets文件夹中。通过下面代码即可解析Json文件中存储的数据。在编辑器模式和发布安卓端均可使用。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LitJson;
using System;

public class ReadJsonDataManager : MonoBehaviour {


    public static ReadJsonDataManager _inStance;

    private const string scene1JsonPathName = "Data.json";
    private DataJson dataJson;
    private void Awake()
    {
        _inStance = this;     
    }

    // Use this for initialization
    void Start () {
          ReadJsonData();
    }
    public static string getTextForStreamingAssets(string path)
    {
        string localPath = "";
        if ( Application.platform == RuntimePlatform.Android )
        {
            localPath = Application.streamingAssetsPath + "/"  + path;
        }
        else
        {
            localPath = "file:///" + Application.streamingAssetsPath + "/"+ path;
        }          
        WWW t_WWW = new WWW(localPath);     //格式必须是"ANSI",不能是"UTF-8"

        if ( t_WWW.error != null )
        {
            Debug.LogError("error : " + localPath);
            return "";          //读取文件出错
        }

        while ( !t_WWW.isDone )
        {

        }
        Debug.Log("t_WWW.text=  " + t_WWW.text);
      
        return t_WWW.text;
    }

    public void ReadJsonData() {
        string text = getTextForStreamingAssets(scene1JsonPathName);
        dataJson = null;
        JsonData jsonData = JsonMapper.ToObject(text);
        if ( jsonData != null )
        {
            Debug.Log("JsonData数量"+ jsonData.Count);
            for ( int i = 0; i < jsonData.Count; i++ )
            {
                string triggerGameObjectName = jsonData[i]["triggerGameObject"].ToString();//获得Json中triggerGameObject值
                int gameObjectNum=Convert.ToInt32( jsonData[i]["gameObjectNum"].ToString());//获得Json中gameObjectNum数值 
                bool isRight = Convert.ToBoolean(jsonData[i]["isRight"].ToString());//获取Json中isRight布尔值   
        }
        else {
            Debug.Log("jsonData为空");
        } 
    }
}

你可能感兴趣的:(Unity开发,Android)