How do I get the JsonFX plugin to read a json file from a website?

I’m trying to use the JsonFX plugin to read a .json file from my website.

This code works when testing the game in the Unity editor:

var json : String;
json = File.ReadAllText("test.json");

If my Unity project is located at **C:\UnityProject**, then this code accesses C:\UnityProject\test.json. It works perfectly.

However, in the web player version of my game, I will I need to access a file from my website. I need to do something more like this:

var json : String;
json = File.ReadAllText("http://www.mywebsite.com/test.json");

Of course, the above code doesn’t work. It tries to access C:\UnityProject\http:\www.mywebsite.com\test.json, which is totally wrong, because the File.ReadAllText function appends *C:\UnityProject* in front of whatever string I try to pass to it.

How would I get JsonFX to perform ReadAllText on a .json file up on my website?

Are you using the www class ?

Actually, JsonFx doesn’t do I/O. It converts strings to objects, and objects to strings, but getting that data to or from other devices is a job for another library.

For files, File.ReadAllText() and File.WriteAllText() are included in Mono’s System.IO namespace.

For web reads, you can handle most basic requests with Unity’s WWW class.

My mistake! I didn’t realize that I need to use the WWW class. This was the solution:

//Download the JSON file from wherever it is on the Internet

function Step1()
{
	jsonFromWeb = new WWW ("test.com/test.json");

	yield jsonFromWeb;
	
	Step2();
}

//If we're in the editor, read the file from our hard drive.
//If we're in the web player, read the file that we downloaded from the Internet.

function Step2()
{
  	var json : String;
	
	#if UNITY_EDITOR
        json = File.ReadAllText("test.json");
	#endif
	
	#if UNITY_WEBPLAYER
		json = jsonFromWeb.text;
	#endif
}

That did the trick!

Thanks for cluing me in to this WWW thing - I had no idea that it existed until today!

It’s all good. Glad to see you’ve got it working. Appreciate you posting sample code, too; handy if this turns up for anybody else searching the same question!