Recently I used JSON a lot and I'd like to share some knowledge about it.
Here I'm using MiniJSON (link) because I prefer C# rather than JS (this one make me sick!).JSON is a... string :) And it can have our arrays, dictionaries, variables and other crazy things. And this is all about it, but if you like reading you should go to Wikipedia and read all about it :P
Okey, you know what JSON is (or not) so now I can tell you how to use it.
First we have to add some usings at the beginnig.
using System.Collections.Generic;Now we need to create Dictionary. This will be our storage.
using MiniJSON;
Dictionary<string, object> dictionary = new Dictionary<string, object>();Great! Next we need some variables.
int intNum = 6;
float floNum = 3.14f;
string word = "Some random text";
int[] decArr = new int[2] {6, 3};And we need to add them to our dictionary.
float[] floArr = new float[2] {3.14f, 1.23f};
string[] words = new string[3] {"Yey", "Nope", "Wow"};
dictionary.Add("intNum", intNum);
dictionary.Add("floNum", floNum);
dictionary.Add("word", word);
dictionary.Add("intArr", intArr);So we have dictionary with some variables within it. So let's turn it into JSON! ];->
dictionary.Add("floArr", floArr);
dictionary.Add("words", words);
string ourJSON = Json.Serialize(dictionary);Now it's easy to save it into register. I hope you know about PlayerPrefs in Unity :)
PlayerPrefs.SetString("ourJSON", ourJSON );
That was easy part. And now how to turn it back to our variables?!
First we need our JSON back and turn it into Dictionary.
string ourJson = PlayerPrefs.GetString("ourJSON");And it's almost good :) Let's get our non-array variables. Because we casting from object variables we have to use 64-bit types.
Dictionary<string, object> dict = new Dictionary<string, object>();
dict = Json.Deserialize(ourJson) as Dictionary<string, object>;
object obj = dict["intNum"];
long lonNum = (long)obj;
obj = dict["floNum"];
double douNum = (double)obj;
obj = dict["word"];But you can easily turn it into 32-bit. For example:
string word = (string)obj;
int intNum = (int)lonNum;It's time for arrays.. As we can't do it easily we have to do little trick ;)
obj = dict["intArr"];
long[] lonArr = new long[(obj as ICollection).Count];
(obj as ICollection).CopyTo(lonArr, 0);
obj = dict["floArr"];
double[] douArr = new double[(obj as ICollection).Count];
(obj as ICollection).CopyTo(douArr, 0);
obj = dict["words"];And if you need just 32-bit arrays you have to do this.
string[] words = new string[(obj as ICollection).Count];
(obj as ICollection).CopyTo(words, 0);
int[] intArr = new int[lonArr.Length];
for (int i = 0; i < lonArr.Length; i++) {
intArr[i] = (int)lonArr[i];
}
Bravo! Now you know how to use JSON with PlayerPrefs in Unity3D!
Have fun and make a good use of it :)
If you need my script here you can download it. :)
This is a old post but i dont care!!!! Omg this is amazing!! Your way og explaining makes this so easy!! THX mate!! I love your mind
ReplyDelete