From Unify Community Wiki
Revision as of 01:10, 9 October 2010 by Scone (Talk | contribs)

Jump to: navigation, search



Matt Schoen of Defective Studios


Download JSONObject.zip


I came across the need to send structured data to and from a server on one of my projects, and figured it would be worth my while to use JSON. When I looked into the issue, I tried a few of the C# implementations listed on [json.org], but found them to be too complicated, or used part of the .NET framework not accessible from Unity scripts. So, I've written a very simple JSONObject class, which can be generically used to encode/decode data into a simple container. This page assumes that you know what JSON is, and how it works. It's rather simple, just go to json.org for a visual description of the encoding format.


Users should not have to modify the JSONObject class themselves, and must follow the very simple proceedures outlined below:

Sample data (in JSON format): {"field1":0.5,"field2":"sampletext","field3":[1,2,3]}


It should be pretty obvious what this parser can and cannot do. If anyone reading this is a JSON buff (is there such a thing?) please feel free to expand and modify the parser to be more compliant. Currently I am using the .NET System.Convert namespace functions for parsing the data itself. It parses strings and numbers, which was all that I needed of it, but unless the formatting is supported by System.Convert, it may not incorporate all proper JSON strings. Also, having never written a JSON parser before, I don't doubt that I could improve the efficiency or correctness of the parser. It serves my purpose, and hopefully will help you with your project! Let me know if you make any improvements :)


Encoding is something of a hard-coded process. This is because I have no idea what your data is! It would be great if this were some sort of interface for taking an entire class and encoding it's number/string fields, but it's not. I've come up with a few clever ways of using loops and/or recursive methods to cut down of the amount of code I have to write when I use this tool, but they're pretty project-specific.

<csharp> //Note: your data can only be numbers and strings. This is not a solution for object serialization or anything like that. JSONObject j = new JSONObject(JSONObject.Type.OBJECT); //number j.keys.Add("field1"); j.list.Add(0.5); //string j.keys.Add("field2"); j.list.Add("sampletext"); //array j.keys.Add("field3");

JSONObject arr = new JSONObject(JSONObject.Type.ARRAY); arr.list.Add(1); arr.list.Add(2); arr.list.Add(3);


string encodedString = j.print(); </csharp>


Decoding is much simpler on the input end, and again, what you do with the JSONObject will vary on a per-project basis. One of the more complicated way to extract the data is with a recursive function, as drafted below. Calling the constructor with a properly formatted JSON string will return the root object (or array) containing all of its children, in one neat reference! The data is in a public ArrayList called list, with a matching key list (called keys!) if the root is an Object. If that's confusing, take a glance over the following code and the print() method in the JSONOBject class. If there is an error in the JSON formatting (or if there's an error with my code!) the debug console will read "improper JSON formatting".

<csharp> string encodedString = "{\"field1\":0.5,\"field2\":\"sampletext\",\"field3\":[1,2,3]}"; JSONObject j = new JSONObject(encodedString); accessData(j); //access data (and print it) void accessData(JSONObject obj){ switch(obj.type){ case JSONObject.Type.OBJECT: for(int i = 0; i < obj.list.Count; i++){ string key = (string)obj.keys[i]; JSONObject j = (JSONObject)obj.list[i]; Debug.Log(key); accessData(j); } break; case JSONObject.Type.ARRAY: foreach(JSONObject j in obj.list){ accessData(j); } break; case JSONObject.Type.STRING: Debug.Log(obj.str); break; case JSONObject.Type.NUMBER: Debug.Log(obj.n); break; case JSONObject.Type.BOOL: Debug.Log(obj.n); break; case JSONObject.Type.NULL: Debug.Log(obj.n); break;

} } </csharp>

The JSONObject class

<csharp> /*

* http://www.opensource.org/licenses/lgpl-2.1.php
* JSONObject class
* for use with Unity
* Matt Schoen 2010

using UnityEngine; using System.Collections;

public class JSONObject { public ArrayList keys; public enum Type { STRING, NUMBER, OBJECT, ARRAY, BOOL, NULL } public JSONObject parent; public Type type; public ArrayList list; public string str; public double n; public bool b;

public JSONObject() { } public JSONObject(JSONObject.Type t) { type = t; switch(t) { case Type.ARRAY: list = new ArrayList(); break; case Type.OBJECT: list = new ArrayList(); keys = new ArrayList(); break; } } public JSONObject(bool b){ type = Type.BOOL; this.b = b; } public JSONObject(float f){ type = Type.NUMBER; this.n = f; } public JSONObject() { type = Type.NULL; } public JSONObject(string str) { //create a new JSONObject from a string (this will also create any children, and parse the whole string) if(str.Length > 0) { if(str == "true") { type = Type.BOOL; b = true; } else if(str == "false") { type = Type.BOOL; b = false; } else if(str == "null") { type = Type.NULL; } else if(str[0] == '"') { type = Type.STRING; this.str = str.Substring(1, str.Length - 2); } else { try { n = System.Convert.ToDouble(str); type = Type.NUMBER; } catch(System.FormatException) { int token_tmp = 0; /* * Checking for the following formatting (www.json.org) * object - {"field1":value,"field2":value} * array - [value,value,value] * value - string - "string" * - number - 0.0 * - bool - true -or- false * - null - null */ switch(str[0]) { case '{': type = Type.OBJECT; keys = new ArrayList(); list = new ArrayList(); break; case '[': type = JSONObject.Type.ARRAY; list = new ArrayList(); break; default: type = Type.NULL; Debug.Log("improper JSON formatting"); return; } int depth = 0; bool openquote = false; for(int i = 1; i < str.Length; i++) { if(str[i] == '"') openquote = !openquote; if(str[i] == '[' || str[i] == '{') depth++; if(depth == 0 && !openquote) { if(str[i] == ':') { keys.Add(str.Substring(token_tmp + 2, i - token_tmp - 3)); token_tmp = i; } if(str[i] == ',') { list.Add(new JSONObject(str.Substring(token_tmp + 1, i - token_tmp - 1))); token_tmp = i; } if(str[i] == ']' || str[i] == '}') list.Add(new JSONObject(str.Substring(token_tmp + 1, i - token_tmp - 1))); } if(str[i] == ']' || str[i] == '}') depth--; } } } } else { type = Type.NULL; } } public string print() { //Convert the JSONObject into a stiring string str = ""; switch(type) { case Type.STRING: str = "\"" + this.str + "\""; break; case Type.NUMBER: str += n; break; case JSONObject.Type.OBJECT: if(list.Count > 0){ str = "{"; for(int i = 0; i < list.Count; i++) { string key = (string)keys[i]; str += "\"" + key + "\":"; JSONObject obj = (JSONObject)list[i]; str += obj.print() +","; } str = str.Substring(0, str.Length - 1); str += "}"; break; } case JSONObject.Type.ARRAY: if(list.Count > 0){ str = "["; foreach(JSONObject obj in list) { str += obj.print() + ","; } str = str.Substring(0, str.Length - 1); str += "]"; break; } case Type.BOOL: str += b; break; case Type.NULL: str = "null"; break; } return str; } public static implicit operator bool(JSONObject j) { return j != null; } } </csharp>

Personal tools