Устройства Android не читают файл JSON, но Unity может его прочитать. Почему?

Я использую файл Json/LitJson, чтобы прочитать вопрос базы данных и ответить на мои викторины.

Он работает без каких-либо ошибок в Unity, но после того, как я встроил его в APK, он не работал должным образом на устройствах Android, из-за чего викторины не вышли после того, как я его запустил. Я использую Android-телефон MI3, затем я попробовал его и в BlueStacks. Это не работает на обеих платформах (ну, они оба Android).

Я не очень уверен, что это проблема с устройствами Android или моя проблема с кодом файла Json. Ниже приведен мой код для чтения файла Json. Цените любую помощь. Спасибо.

void Start(){//start reading Json file
    score = 0;
    nextQuestion = true;
    jsonString = File.ReadAllText (Application.dataPath + "/quiz.json");
    questionData = JsonMapper.ToObject (jsonString);
    //StartCoroutine ("Json");
}



public void OnClick(){//get the question and answer from Json after clicking

    if (nextQuestion) {

        GameObject[] destroyAnswer = GameObject.FindGameObjectsWithTag ("Answer");
        if (destroyAnswer != null) {
            for (int x=0; x<destroyAnswer.Length; x++) {
                DestroyImmediate (destroyAnswer [x]);
            }
        }

        qq.GetComponentInChildren<Text> ().text = questionData ["data"] [questionNumber] ["question"].ToString ();

        for (int i=0; i<questionData["data"][questionNumber]["answer"].Count; i++) {
            GameObject answer = Instantiate (answerPrefab);
            answer.GetComponentInChildren<Text> ().text = questionData ["data"] [questionNumber] ["answer"] [i].ToString ();
            Transform answerC = GameObject.Find ("GameObject").GetComponent<Transform> ();
            answer.transform.SetParent (answerC);

            string x = i.ToString ();

            if (i == 0) {
                answer.name = "CorrectAnswer";
                answer.GetComponent<Button> ().onClick.AddListener (() => Answer ("0"));
            } else {
                answer.name = "WrongAnswer" + x;
                answer.GetComponent<Button> ().onClick.AddListener (() => Answer (x));
            }
            answer.transform.SetSiblingIndex (Random.Range (0, 3));
        }

        questionNumber++;
        nextQuestion = false;
        clickAns = true;
    }

}

Мой JSON-файл:

{
"data": [
{
    "id": "1",
    "question": "Cape Warthog and Dodo come from which country?",
    "answer": [
        "Africa",
        "India",
        "Philippines",
        "Australia"
    ]
}, {
    "id": "2",
    "question": "Dama Gazelle live in what place?",
    "answer": [
        "Sahara dessert",
        "Africa beach",
        "Rain forest",
        "South pole"
    ]
}, {
    "id": "3",
    "question": "Why did the Sabertooth Tiger extinct",
    "answer": [
        "overhunting",
        "Habitat loss",
        "Natural polution",
        "Diseases"
    ]
}, {
    "id": "4",
    "question": "Wolly Mammoth resemblance to which animal?",
    "answer": [
        "Elephant",
        "Tiger",
        "Sheep",
        "Giraffe"
    ]
}, {
    "id": "5",
    "question": "How big Tasmanian Tiger mouth would open?",
    "answer": [
        "120 degree angle",
        "110 degree angle",
        "100 degree angle",
        "130 degree angle"
    ]
}, {
    "id": "6",
    "question": "Greak Auk could not fly because it has ..... ?",
    "answer": [
        "Tiny wing",
        "Heavy body",
        "Big head",
        "Large feet"
    ]
}, {
    "id": "7",
    "question": "PyreneanIbex make their homes at where ? ",
    "answer" : [
        "Cliffs",
        "Caves",
        "Forest",
        "Waterfall"
    ]
}, {
    "id": "8",
    "question": "What are endangered animals?",
    "answer": [
        "Animals that going to extinct",
        "Animals that flys",
        "Animals that are dangerous",
        "Animals that have 4 legs"
    ]
}
]
}

person Kurogane    schedule 16.04.2016    source источник
comment
Как выглядит файл JSON? Какова структура объекта QuestionData?   -  person Egor    schedule 16.04.2016
comment
Я отредактировал свой вопрос. Спасибо   -  person Kurogane    schedule 17.04.2016
comment
вы получаете какие-либо отзывы в logcat?   -  person Pooya    schedule 17.04.2016
comment
что такое логкэт? Он работает без ошибок на Unity, но не может работать на телефоне.   -  person Kurogane    schedule 17.04.2016


Ответы (1)


У меня та же проблема. Я практиковался в викторине 2 из сеанса Unity Live. Вам нужно кодировать по-другому для Android. Я поместил свой файл data.json в папку StreamingAssets внутри папки Assets. Он отлично работает в редакторе Unity, но проблема в том, что Папка StreamingAssets не существует на Android.

На Android файлы содержатся в сжатом файле .jar (по сути, это тот же формат, что и стандартные файлы, сжатые zip). Это означает, что если вы не используете класс Unity WWW для извлечения файла, вам потребуется использовать дополнительное программное обеспечение, чтобы заглянуть внутрь архива .jar и получить файл.

Вот мой пример кода; вызовите LoadGameData() из Start().

private void LoadGameData()
{
    string filePath = "";

    #if UNITY_EDITOR
    filePath = Application.dataPath + "/StreamingAssets/data.json";
    if (File.Exists (filePath)) {

        string dataAsJson = File.ReadAllText (filePath);
        GameData loadedData = JsonUtility.FromJson<GameData> (dataAsJson);

        allRoundData = loadedData.allRoundData;
    } else {
        Debug.LogError ("Can not load game data!");
    }
    #elif UNITY_ANDROID
    filePath = "jar:file://" + Application.dataPath + "!/assets/data.json";
    StartCoroutine(GetDataInAndroid(filePath));
    #endif
}

IEnumerator GetDataInAndroid(string url) 
{
    WWW www = new WWW(url);
    yield return www;
    if (www.text != null) {

        string dataAsJson = www.text;
        GameData loadedData = JsonUtility.FromJson<GameData> (dataAsJson);

        allRoundData = loadedData.allRoundData;
    } else {
        Debug.LogError ("Can not load game data!");
    }
}
person AFA    schedule 24.02.2017