如何为ios和android的unity3D中的文件保存JSON响应

时间:2013-05-16 06:39:54

标签: json mobile unity3d

我正在使用Unity3D为ios和android开发2D手机游戏。 游戏需要将JSON响应保存到文件中。 我使用NGUI和MiniJSON。 我想知道如何实现从www函数开始获取JSOn响应并将其保存到文件(包括路径)并从其他脚本加载它。 如果它太多了,那就给我一个例子。

谢谢

1 个答案:

答案 0 :(得分:1)

我还没有测试过代码,但它可能会给你一个想法: - )

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;

public class WWWJsonTest : MonoBehaviour
{
    private const float SECONDS_BEFORE_TIMEOUT = 10;

    private const string URL = "INSERT URL HERE";

    private const string FILE_PATH = "INSERT FILE PATH";

    public void DownloadAndSave()
    {
        StartCoroutine(DownloadCoroutine());
    }

    public Dictionary<object, object> GetSavedData()
    {
        // Use ReadContents() and do your MiniJSON magic here
        return null;    
    }

    private IEnumerator DownloadCoroutine()
    {
        var requestHeaders = new Hashtable()
        {
            { "Connection", "close"},
            { "Accept", "application/json"}
        };

        using(var request = new WWW(URL, null, requestHeaders))
        {
            float timeStarted = Time.realtimeSinceStartup;

            while(!request.isDone)
            {
                // Check if the download times out
                if(Time.realtimeSinceStartup - timeStarted > SECONDS_BEFORE_TIMEOUT)
                {
                    Debug.Log("Download timed out");
                    yield break;
                }

                yield return null;
            }

            // Check for other errors
            if(request.error != null)
            {
                Debug.Log(request.error);

                yield break;
            }


            SaveContents(request.text);
        }
    }

    private string ReadContents()
    {
        string ret;

        using(FileStream fs = new FileStream(FILE_PATH, FileMode.Open))
        {
            BinaryReader fileReader = new BinaryReader(fs);

            ret = fileReader.ReadString();

            fs.Close();
        }

        return ret;
    }

    private void SaveContents(string text)
    {
        using(FileStream fs = new FileStream(FILE_PATH, FileMode.Create))
        {
            BinaryWriter fileWriter = new BinaryWriter(fs);

            fileWriter.Write(text);

            fs.Close();
        }
    }   
}