Why does JsonUtility fails miserably on Android?

Hi!

I was using Json to load text from different languages on my game.
It worked on the Editor.
I built an APK, installed it on my phone and nothing happens.

The game didn’t crash, it just don’t load the json.

I worked it around.

Instead of having a Json file, then loading it, then parsing it to my object, I made it directly on an object, and when I change the language I just change the object.

No hard feelings.

But WHY JsonUtility doesn’t work on Android? Is it because of StreamingAssets folder? Is it possible to build an APK with a JSON in it?

TextAsset is the class I used to parse the Json. It is just a bunch of public strings, no functions at all.

Below is the code that works on Editor, but not on Android:

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

public class LanguagePack : MonoBehaviour {
	public TextAsset txt;
	string lang; //language string, (en, jp, de...)

	void Start(){
		DontDestroyOnLoad (this.gameObject);
		lang = GetCurLang ();
		txt = loadJson ();
	}

	public string GetCurLang(){
		return PlayerPrefs.GetString ("curLang");
	}

	public void SetCurLang(string l){
		loadComplete = false;
		Debug.Log ("Language changed to " + l);
		PlayerPrefs.SetString ("curLang", l);
		lang = l;
		txt = loadJson ();
	}

	public TextAsset loadJson(){
		string dataFileName = lang + ".json";
		//string dataFileName = "pt-br.json";
		string filePath = Path.Combine (Application.streamingAssetsPath, dataFileName);
		if(File.Exists(filePath)){
			string jsonData = File.ReadAllText (filePath);
			TextAsset loadedData = JsonUtility.FromJson<TextAsset> (jsonData);
			loadComplete = true;
			return loadedData;
		} else {
			Debug.LogError ("JSON not found");
		}
		return null;
	}
}

P.S.: I lied about my feelings.

Hello there,

My guess is that the problem lies with the Streaming Assets Path rather than with JsonUtility. If I remember correctly, it behaves differently on Android because it gets compressed to a JAR file.
This post may put you on the right path.

EDIT: If you are only going to be loading data, you could also use Resources.Load(). That’s what I usually do for locally-stored translation systems.

Hope that helps!

Cheers,

~LegendBacon