JSONObject

From Unify Community Wiki
(Difference between revisions)
Jump to: navigation, search
(The JSONObject class)
(Download)
 
(4 intermediate revisions by one user not shown)
Line 3: Line 3:
  
 
==Download==
 
==Download==
[[Media:JSONObject.zip|Download JSONObject.zip]]
+
Use the [https://github.com/mtschoen/JSONObject github repository] or [http://u3d.as/1Rh get it on the AssetStore]
  
 
= Intro =
 
= Intro =
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 [http://json.org json.org], but found them to be too complicated.  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.
+
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 [http://json.org json.org], but found them to be too complicated to work with and expand upon.  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.
  
 
As an aside, this class is pretty central to the [[AssetCloud]] content management system, from Defective Studios.
 
As an aside, this class is pretty central to the [[AssetCloud]] content management system, from Defective Studios.
  
Update: The code has been updated to version 1.3 to incorporate user-submitted patches and bug reports.  This fixes issues dealing with whitespace in the format, as well as empty arrays and objects.
+
Update: The code has been updated to version 1.4 to incorporate user-submitted patches and bug reports.  This fixes issues dealing with whitespace in the format, as well as empty arrays and objects, and escaped quotes within strings.
  
 
= Usage =
 
= Usage =
 
Users should not have to modify the JSONObject class themselves, and must follow the very simple proceedures outlined below:
 
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]}
+
Sample data (in JSON format):
 +
<nowiki>
 +
{
 +
"TestObject": {
 +
"SomeText": "Blah",
 +
"SomeObject": {
 +
"SomeNumber": 42,
 +
"SomeBool": true,
 +
"SomeNull": null
 +
},
 +
 +
"SomeEmptyObject": { },
 +
"SomeEmptyArray": [ ],
 +
"EmbeddedObject": "{\"field\":\"Value with \\\"escaped quotes\\\"\"}"
 +
}
 +
}</nowiki>
  
 
= Features =
 
= Features =
Line 21: Line 36:
 
*Decode JSON-formatted strings into a usable data structure
 
*Decode JSON-formatted strings into a usable data structure
 
*Encode structured data into a JSON-formatted string
 
*Encode structured data into a JSON-formatted string
*Interoperable with System.Collections.Generic.Dictionary
+
*Interoperable with Dictionary and WWWForm
 +
*Optimized parse/stringify functions -- minimal (unavoidable) garbage creation
 +
*Asynchronous stringify function for serializing lots of data without frame drops
 +
*MaxDepth parsing will skip over nested data that you don't need
 +
*Special (non-compliant) "Baked" object type can store stringified data within parsed objects
 
*Copy to new JSONObject
 
*Copy to new JSONObject
 
*Merge with another JSONObject (experimental)
 
*Merge with another JSONObject (experimental)
Line 28: Line 47:
 
*Switch between double and float for numeric storage depending on level of precision needed (and to ensure that numbers are parsed/stringified correctly)
 
*Switch between double and float for numeric storage depending on level of precision needed (and to ensure that numbers are parsed/stringified correctly)
 
*Supports Infinity and NaN values
 
*Supports Infinity and NaN values
 +
*JSONTemplates static class provides serialization functions for common classes like Vector3, Matrix4x4
 +
*Object pool implementation (experimental)
 +
*Handy JSONChecker window to test parsing on sample data
  
 
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 :)
 
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 :)
 +
 +
Also, you JSON buffs (really, who would admit to being a JSON buff...) might also notice from my feature list that this thing isn't exactly to specifications. Here is where it differs:
 +
*"a string" is considered valid JSON.  There is an optional "strict" parameter to the parser which will bomb out on such input, in case that matters to you.
 +
*The "Baked" mode is totally made up.
 +
*The "MaxDepth" parsing is totally made up.
 +
*NaN and Infinity aren't officially supported by JSON ([http://stackoverflow.com/questions/1423081/json-left-out-infinity-and-nan-json-status-in-ecmascript read more] about this issue... I lol'd @ the first comment on the first answer)
 +
*I have no idea about edge cases in my parsing strategy.  I have been using this code for about 3 years now and have only had to modify the parser because other people's use cases (still valid JSON) didn't parse correctly.  In my experience, anything that this code generates is parsed just fine.
  
 
== Encoding ==
 
== Encoding ==
Line 35: Line 64:
 
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.
 
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.
  
Note: This section used to be WRONG!
+
Note: This section used to be WRONG! And now it's OLD! Will update later... this will all still work, but there are now a couple of ways to skin this cat.
  
 
<syntaxhighlight lang="csharp">
 
<syntaxhighlight lang="csharp">
Line 125: Line 154:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
===New! (O(n)) Random access!===
+
===Not So New! (O(n)) Random access!===
 
I've added a string and int [] index to the class, so you can now retrieve data as such (from above):
 
I've added a string and int [] index to the class, so you can now retrieve data as such (from above):
 
<syntaxhighlight lang="csharp">
 
<syntaxhighlight lang="csharp">
Line 134: Line 163:
 
----
 
----
  
=The JSONObject class=
+
=The Code=
<syntaxhighlight lang="csharp">
+
The code is now available on [https://github.com/mtschoen/JSONObject github].
#define PRETTY //Comment out when you no longer need to read JSON to disable pretty print system-wide
+
#define USEFLOAT //Use floats for numbers instead of doubles (enable if you're getting too many significant digits in string output)
+
  
using UnityEngine;
+
=Change Log=
using System.Collections;
+
==v1.4==
using System.Collections.Generic;
+
Big update!
 
+
*Better GC performanceEnough of that garbage!
/*
+
**Remaining culprits are internal garbage from StringBuilder.Append/AppendFormat, String.Substring, List.Add/GrowIfNeeded, Single.ToString
* http://www.opensource.org/licenses/lgpl-2.1.php
+
*Added asynchronous Stringify function for serializing large amounts of data at runtime without frame drops
* JSONObject class
+
*Added Baked type
* for use with Unity
+
*Added MaxDepth to parsing function
* Copyright Matt Schoen 2010 - 2013
+
*Various cleanup refactors recommended by ReSharper
*/
+
 
+
public class JSONObject {
+
const int MAX_DEPTH = 1000;
+
const string INFINITY = "\"INFINITY\"";
+
const string NEGINFINITY = "\"NEGINFINITY\"";
+
const string NaN = "\"NaN\"";
+
public static char[]  WHITESPACE = new char[] { ' ', '\r', '\n', '\t' };
+
public enum Type { NULL, STRING, NUMBER, OBJECT, ARRAY, BOOL }
+
public bool isContainer { get { return (type == Type.ARRAY || type == Type.OBJECT); } }
+
public JSONObject parent;
+
public Type type = Type.NULL;
+
public int Count {
+
get {
+
if(list == null)
+
return -1;
+
return list.Count;
+
}
+
}
+
//TODO: Switch to list
+
public List<JSONObject> list;
+
public List<string> keys;
+
public string str;
+
#if USEFLOAT
+
public float n;
+
public float f {
+
get {
+
return n;
+
}
+
}
+
#else
+
public double n;
+
public float f {
+
get {
+
return (float)n;
+
}
+
}
+
#endif
+
public bool b;
+
public delegate void AddJSONConents(JSONObject self);
+
 
+
public static JSONObject nullJO { get { return new JSONObject(JSONObject.Type.NULL); } } //an empty, null object
+
public static JSONObject obj { get { return new JSONObject(JSONObject.Type.OBJECT); } } //an empty object
+
public static JSONObject arr { get { return new JSONObject(JSONObject.Type.ARRAY); } } //an empty array
+
 
+
public JSONObject(JSONObject.Type t) {
+
type = t;
+
switch(t) {
+
case Type.ARRAY:
+
list = new List<JSONObject>();
+
break;
+
case Type.OBJECT:
+
list = new List<JSONObject>();
+
keys = new List<string>();
+
break;
+
}
+
}
+
public JSONObject(bool b) {
+
type = Type.BOOL;
+
this.b = b;
+
}
+
public JSONObject(float f) {
+
type = Type.NUMBER;
+
this.n = f;
+
}
+
public JSONObject(Dictionary<string, string> dic) {
+
type = Type.OBJECT;
+
keys = new List<string>();
+
list = new List<JSONObject>();
+
foreach(KeyValuePair<string, string> kvp in dic) {
+
keys.Add(kvp.Key);
+
list.Add(new JSONObject { type = Type.STRING, str = kvp.Value });
+
}
+
}
+
public JSONObject(Dictionary<string, JSONObject> dic) {
+
type = Type.OBJECT;
+
keys = new List<string>();
+
list = new List<JSONObject>();
+
foreach(KeyValuePair<string, JSONObject> kvp in dic) {
+
keys.Add(kvp.Key);
+
list.Add(kvp.Value);
+
}
+
}
+
public JSONObject(AddJSONConents content) {
+
content.Invoke(this);
+
}
+
public JSONObject(JSONObject[] objs) {
+
type = Type.ARRAY;
+
list = new List<JSONObject>(objs);
+
}
+
//Convenience function for creating a JSONObject containing a stringThis is not part of the constructor so that malformed JSON data doesn't just turn into a string object
+
public static JSONObject StringObject(string val) { return new JSONObject { type = JSONObject.Type.STRING, str = val }; }
+
public void Absorb(JSONObject obj) {
+
list.AddRange(obj.list);
+
keys.AddRange(obj.keys);
+
str = obj.str;
+
n = obj.n;
+
b = obj.b;
+
type = obj.type;
+
}
+
public JSONObject() { }
+
#region PARSE
+
public JSONObject(string str, bool strict = false) { //create a new JSONObject from a string (this will also create any children, and parse the whole string)
+
if(str != null) {
+
str = str.Trim(WHITESPACE);
+
if(strict) {
+
if(str[0] != '[' && str[0] != '{') {
+
type = Type.NULL;
+
Debug.LogWarning("Improper (strict) JSON formatting.  First character must be [ or {");
+
return;
+
}
+
}
+
if(str.Length > 0) {
+
if(string.Compare(str, "true", true) == 0) {
+
type = Type.BOOL;
+
b = true;
+
} else if(string.Compare(str, "false", true) == 0) {
+
type = Type.BOOL;
+
b = false;
+
} else if(string.Compare(str, "null", true) == 0) {
+
type = Type.NULL;
+
#if USEFLOAT
+
} else if(str == INFINITY) {
+
type = Type.NUMBER;
+
n = float.PositiveInfinity;
+
} else if(str == NEGINFINITY) {
+
type = Type.NUMBER;
+
n = float.NegativeInfinity;
+
} else if(str == NaN) {
+
type = Type.NUMBER;
+
n = float.NaN;
+
#else
+
} else if(str == INFINITY) {
+
type = Type.NUMBER;
+
n = double.PositiveInfinity;
+
} else if(str == NEGINFINITY) {
+
type = Type.NUMBER;
+
n = double.NegativeInfinity;
+
} else if(str == NaN) {
+
type = Type.NUMBER;
+
n = double.NaN;
+
#endif
+
} else if(str[0] == '"') {
+
type = Type.STRING;
+
this.str = str.Substring(1, str.Length - 2);
+
} else {
+
try {
+
#if USEFLOAT
+
n = System.Convert.ToSingle(str);
+
#else
+
n = System.Convert.ToDouble(str);
+
#endif
+
type = Type.NUMBER;
+
} catch(System.FormatException) {
+
int token_tmp = 1;
+
/*
+
* 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
+
*/
+
int offset = 0;
+
switch(str[offset]) {
+
case '{':
+
type = Type.OBJECT;
+
keys = new List<string>();
+
list = new List<JSONObject>();
+
break;
+
case '[':
+
type = JSONObject.Type.ARRAY;
+
list = new List<JSONObject>();
+
break;
+
default:
+
type = Type.NULL;
+
Debug.LogWarning("improper JSON formatting:" + str);
+
return;
+
}
+
string propName = "";
+
bool openQuote = false;
+
bool inProp = false;
+
int depth = 0;
+
while(++offset < str.Length) {
+
if(System.Array.IndexOf<char>(WHITESPACE, str[offset]) > -1)
+
continue;
+
if(str[offset] == '\"') {
+
if(openQuote) {
+
if(!inProp && depth == 0 && type == Type.OBJECT)
+
propName = str.Substring(token_tmp + 1, offset - token_tmp - 1);
+
openQuote = false;
+
} else {
+
if(depth == 0 && type == Type.OBJECT)
+
token_tmp = offset;
+
openQuote = true;
+
}
+
}
+
if(openQuote)
+
continue;
+
if(type == Type.OBJECT && depth == 0) {
+
if(str[offset] == ':') {
+
token_tmp = offset + 1;
+
inProp = true;
+
}
+
}
+
+
if(str[offset] == '[' || str[offset] == '{') {
+
depth++;
+
} else if(str[offset] == ']' || str[offset] == '}') {
+
depth--;
+
}
+
//if  (encounter a ',' at top level)  || a closing ]/}
+
if((str[offset] == ',' && depth == 0) || depth <  0) {
+
inProp = false;
+
string inner = str.Substring(token_tmp, offset - token_tmp).Trim(WHITESPACE);
+
if(inner.Length > 0) {
+
if(type == Type.OBJECT)
+
keys.Add(propName);
+
list.Add(new JSONObject(inner));
+
}
+
token_tmp = offset + 1;
+
}
+
}
+
}
+
}
+
} else type = Type.NULL;
+
} else type = Type.NULL; //If the string is missing, this is a null
+
}
+
#endregion
+
public bool IsNumber { get { return type == Type.NUMBER; } }
+
public bool IsNull { get { return type == Type.NULL; } }
+
public bool IsString { get { return type == Type.STRING; } }
+
public bool IsBool { get { return type == Type.BOOL; } }
+
public bool IsArray { get { return type == Type.ARRAY; } }
+
public bool IsObject { get { return type == Type.OBJECT; } }
+
public void Add(bool val) { Add(new JSONObject(val)); }
+
public void Add(float val) { Add(new JSONObject(val)); }
+
public void Add(int val) { Add(new JSONObject(val)); }
+
public void Add(string str) { Add(StringObject(str)); }
+
public void Add(AddJSONConents content) { Add(new JSONObject(content)); }
+
public void Add(JSONObject obj) {
+
if(obj) { //Don't do anything if the object is null
+
if(type != JSONObject.Type.ARRAY) {
+
type = JSONObject.Type.ARRAY; //Congratulations, son, you're an ARRAY now
+
if(list == null)
+
list = new List<JSONObject>();
+
}
+
list.Add(obj);
+
}
+
}
+
public void AddField(string name, bool val) { AddField(name, new JSONObject(val)); }
+
public void AddField(string name, float val) { AddField(name, new JSONObject(val)); }
+
public void AddField(string name, int val) { AddField(name, new JSONObject(val)); }
+
public void AddField(string name, AddJSONConents content) { AddField(name, new JSONObject(content)); }
+
public void AddField(string name, string val) { AddField(name, StringObject(val)); }
+
public void AddField(string name, JSONObject obj) {
+
if(obj) { //Don't do anything if the object is null
+
if(type != JSONObject.Type.OBJECT) {
+
keys = new List<string>();
+
if(type == Type.ARRAY) {
+
for(int i = 0; i < list.Count; i++)
+
keys.Add(i + "");
+
} else if(list == null)
+
list = new List<JSONObject>();
+
type = JSONObject.Type.OBJECT; //Congratulations, son, you're an OBJECT now
+
}
+
keys.Add(name);
+
list.Add(obj);
+
}
+
}
+
public void SetField(string name, bool val) { SetField(name, new JSONObject(val)); }
+
public void SetField(string name, float val) { SetField(name, new JSONObject(val)); }
+
public void SetField(string name, int val) { SetField(name, new JSONObject(val)); }
+
public void SetField(string name, JSONObject obj) {
+
if(HasField(name)) {
+
list.Remove(this[name]);
+
keys.Remove(name);
+
}
+
AddField(name, obj);
+
}
+
public void RemoveField(string name) {
+
if(keys.IndexOf(name) > -1) {
+
list.RemoveAt(keys.IndexOf(name));
+
keys.Remove(name);
+
}
+
}
+
public delegate void FieldNotFound(string name);
+
public delegate void GetFieldResponse(JSONObject obj);
+
public void GetField(ref bool field, string name, FieldNotFound fail = null) {
+
if(type == JSONObject.Type.OBJECT) {
+
int index = keys.IndexOf(name);
+
if(index >= 0) {
+
field = list[index].b;
+
return;
+
}
+
}
+
if(fail != null) fail.Invoke(name);
+
}
+
#if USEFLOAT
+
public void GetField(ref float field, string name, FieldNotFound fail = null) {
+
#else
+
public void GetField(ref double field, string name, FieldNotFound fail = null) {
+
#endif
+
if(type == JSONObject.Type.OBJECT) {
+
int index = keys.IndexOf(name);
+
if(index >= 0){
+
field = list[index].n;
+
return;
+
}
+
}
+
if(fail != null) fail.Invoke(name);
+
}
+
public void GetField(ref int field, string name, FieldNotFound fail = null) {
+
if(type == JSONObject.Type.OBJECT) {
+
int index = keys.IndexOf(name);
+
if(index >= 0) {
+
field = (int)list[index].n;
+
return;
+
}
+
}
+
if(fail != null) fail.Invoke(name);
+
}
+
public void GetField(ref uint field, string name, FieldNotFound fail = null) {
+
if(type == JSONObject.Type.OBJECT) {
+
int index = keys.IndexOf(name);
+
if(index >= 0) {
+
field = (uint)list[index].n;
+
return;
+
}
+
}
+
if(fail != null) fail.Invoke(name);
+
}
+
public void GetField(ref string field, string name, FieldNotFound fail = null) {
+
if(type == JSONObject.Type.OBJECT) {
+
int index = keys.IndexOf(name);
+
if(index >= 0) {
+
field = list[index].str;
+
return;
+
}
+
}
+
if(fail != null) fail.Invoke(name);
+
}
+
public void GetField(string name, GetFieldResponse response, FieldNotFound fail = null) {
+
if(response != null && type == Type.OBJECT) {
+
int index = keys.IndexOf(name);
+
if(index >= 0) {
+
response.Invoke(list[index]);
+
return;
+
}
+
}
+
if(fail != null) fail.Invoke(name);
+
}
+
public JSONObject GetField(string name) {
+
if(type == JSONObject.Type.OBJECT)
+
for(int i = 0; i < keys.Count; i++)
+
if((string)keys[i] == name)
+
return (JSONObject)list[i];
+
return null;
+
}
+
public bool HasFields(string[] names) {
+
foreach(string name in names)
+
if(!keys.Contains(name))
+
return false;
+
return true;
+
}
+
public bool HasField(string name) {
+
if(type == JSONObject.Type.OBJECT)
+
for(int i = 0; i < keys.Count; i++)
+
if((string)keys[i] == name)
+
return true;
+
return false;
+
}
+
public void Clear() {
+
type = JSONObject.Type.NULL;
+
if(list != null)
+
list.Clear();
+
if (keys != null)
+
keys.Clear();
+
str = "";
+
n = 0;
+
b = false;
+
}
+
public JSONObject Copy() {
+
return new JSONObject(print());
+
}
+
/*
+
* The Merge function is experimental. Use at your own risk.
+
*/
+
public void Merge(JSONObject obj) {
+
MergeRecur(this, obj);
+
}
+
/// <summary>
+
/// Merge object right into left recursively
+
/// </summary>
+
/// <param name="left">The left (base) object</param>
+
/// <param name="right">The right (new) object</param>
+
static void MergeRecur(JSONObject left, JSONObject right) {
+
if(left.type == JSONObject.Type.NULL)
+
left.Absorb(right);
+
else if(left.type == Type.OBJECT && right.type == Type.OBJECT) {
+
for(int i = 0; i < right.list.Count; i++) {
+
string key = (string)right.keys[i];
+
if(right[i].isContainer) {
+
if(left.HasField(key))
+
MergeRecur(left[key], right[i]);
+
else
+
left.AddField(key, right[i]);
+
} else {
+
if(left.HasField(key))
+
left.SetField(key, right[i]);
+
else
+
left.AddField(key, right[i]);
+
}
+
}
+
} else if(left.type == Type.ARRAY && right.type == Type.ARRAY) {
+
if(right.Count > left.Count) {
+
Debug.LogError("Cannot merge arrays when right object has more elements");
+
return;
+
}
+
for(int i = 0; i < right.list.Count; i++) {
+
if(left[i].type == right[i].type) { //Only overwrite with the same type
+
if(left[i].isContainer)
+
MergeRecur(left[i], right[i]);
+
else {
+
left[i] = right[i];
+
}
+
}
+
}
+
}
+
}
+
public string print(bool pretty = false) {
+
return print(0, pretty);
+
}
+
#region STRINGIFY
+
public string print(int depth, bool pretty = false) { //Convert the JSONObject into a string
+
if(depth++ > MAX_DEPTH) {
+
Debug.Log("reached max depth!");
+
return "";
+
}
+
string str = "";
+
switch(type) {
+
case Type.STRING:
+
str = "\"" + this.str + "\"";
+
break;
+
case Type.NUMBER:
+
#if USEFLOAT
+
if(float.IsInfinity(n))
+
str = INFINITY;
+
else if(float.IsNegativeInfinity(n))
+
str = NEGINFINITY;
+
else if(float.IsNaN(n))
+
str = NaN;
+
#else
+
if(double.IsInfinity(n))
+
str = INFINITY;
+
else if(double.IsNegativeInfinity(n))
+
str = NEGINFINITY;
+
else if(double.IsNaN(n))
+
str = NaN;
+
#endif
+
else
+
str += n;
+
break;
+
 
+
case JSONObject.Type.OBJECT:
+
str = "{";
+
if(list.Count > 0) {
+
#if(PRETTY) //for a bit more readability, comment the define above to disable system-wide
+
if(pretty)
+
str += "\n";
+
#endif
+
for(int i = 0; i < list.Count; i++) {
+
string key = (string)keys[i];
+
JSONObject obj = (JSONObject)list[i];
+
if(obj) {
+
#if(PRETTY)
+
if(pretty)
+
for(int j = 0; j < depth; j++)
+
str += "\t"; //for a bit more readability
+
#endif
+
str += "\"" + key + "\":";
+
str += obj.print(depth, pretty) + ",";
+
#if(PRETTY)
+
if(pretty)
+
str += "\n";
+
#endif
+
}
+
}
+
#if(PRETTY)
+
if(pretty)
+
str = str.Substring(0, str.Length - 1); //BOP: This line shows up twice on purpose: once to remove the \n if readable is true and once to remove the comma
+
#endif
+
str = str.Substring(0, str.Length - 1);
+
}
+
#if(PRETTY)
+
if(pretty && list.Count > 0) {
+
str += "\n";
+
for(int j = 0; j < depth - 1; j++)
+
str += "\t"; //for a bit more readability
+
}
+
#endif
+
str += "}";
+
break;
+
case JSONObject.Type.ARRAY:
+
str = "[";
+
if(list.Count > 0) {
+
#if(PRETTY)
+
if(pretty)
+
str += "\n"; //for a bit more readability
+
#endif
+
foreach(JSONObject obj in list) {
+
if(obj) {
+
#if(PRETTY)
+
if(pretty)
+
for(int j = 0; j < depth; j++)
+
str += "\t"; //for a bit more readability
+
#endif
+
str += obj.print(depth, pretty) + ",";
+
#if(PRETTY)
+
if(pretty)
+
str += "\n"; //for a bit more readability
+
#endif
+
}
+
}
+
#if(PRETTY)
+
if(pretty)
+
str = str.Substring(0, str.Length - 1); //BOP: This line shows up twice on purpose: once to remove the \n if readable is true and once to remove the comma
+
#endif
+
str = str.Substring(0, str.Length - 1);
+
}
+
#if(PRETTY)
+
if(pretty && list.Count > 0) {
+
str += "\n";
+
for(int j = 0; j < depth - 1; j++)
+
str += "\t"; //for a bit more readability
+
}
+
#endif
+
str += "]";
+
break;
+
case Type.BOOL:
+
if(b)
+
str = "true";
+
else
+
str = "false";
+
break;
+
case Type.NULL:
+
str = "null";
+
break;
+
}
+
return str;
+
}
+
#endregion
+
public static implicit operator WWWForm(JSONObject obj){
+
WWWForm form = new WWWForm();
+
for(int i = 0; i < obj.list.Count; i++){
+
string key = i + "";
+
if(obj.type == Type.OBJECT)
+
key = obj.keys[i];
+
string val = obj.list[i].ToString();
+
if(obj.list[i].type == Type.STRING)
+
val = val.Replace("\"", "");
+
form.AddField(key, val);
+
}
+
return form;
+
}
+
public JSONObject this[int index] {
+
get {
+
if(list.Count > index) return (JSONObject)list[index];
+
else return null;
+
}
+
set {
+
if(list.Count > index)
+
list[index] = value;
+
}
+
}
+
public JSONObject this[string index] {
+
get {
+
return GetField(index);
+
}
+
set {
+
SetField(index, value);
+
}
+
}
+
public override string ToString() {
+
return print();
+
}
+
public string ToString(bool pretty) {
+
return print(pretty);
+
}
+
public Dictionary<string, string> ToDictionary() {
+
if(type == Type.OBJECT) {
+
Dictionary<string, string> result = new Dictionary<string, string>();
+
for(int i = 0; i < list.Count; i++) {
+
JSONObject val = (JSONObject)list[i];
+
switch(val.type) {
+
case Type.STRING: result.Add((string)keys[i], val.str); break;
+
case Type.NUMBER: result.Add((string)keys[i], val.n + ""); break;
+
case Type.BOOL: result.Add((string)keys[i], val.b + ""); break;
+
default: Debug.LogWarning("Omitting object: " + (string)keys[i] + " in dictionary conversion"); break;
+
}
+
}
+
return result;
+
} else Debug.LogWarning("Tried to turn non-Object JSONObject into a dictionary");
+
return null;
+
}
+
public static implicit operator bool(JSONObject o) {
+
return (object)o != null;
+
}
+
}
+
</syntaxhighlight>
+
  
 +
==v1.3.2==
 +
*Added support for NaN
 +
*Added strict mode to fail on purpose for improper formatting.  Right now this just means that if the parse string doesn't start with [ or {, it will print a warning and return a null JO.
 +
*Changed infinity and NaN implementation to use float and double instead of Mathf
 +
*Handles empty objects/arrays better
 +
*Added a flag to print and ToString to turn on/off pretty print.  The define on top is now an override to system-wide disable
 +
==Earlier Versions==
 +
I'll fill these in later...
 
[[Category:C Sharp]]
 
[[Category:C Sharp]]
 
[[Category:Scripts]]
 
[[Category:Scripts]]
 
[[Category:Utility]]
 
[[Category:Utility]]
 
[[Category:JSON]]
 
[[Category:JSON]]

Latest revision as of 20:25, 30 June 2015

Contents

[edit] Author

Matt Schoen of Defective Studios

[edit] Download

Use the github repository or get it on the AssetStore

[edit] Intro

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 to work with and expand upon. 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.

As an aside, this class is pretty central to the AssetCloud content management system, from Defective Studios.

Update: The code has been updated to version 1.4 to incorporate user-submitted patches and bug reports. This fixes issues dealing with whitespace in the format, as well as empty arrays and objects, and escaped quotes within strings.

[edit] Usage

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

Sample data (in JSON format):

{
	"TestObject": {
		"SomeText": "Blah",
		"SomeObject": {
			"SomeNumber": 42,
			"SomeBool": true,
			"SomeNull": null
		},
		
		"SomeEmptyObject": { },
		"SomeEmptyArray": [ ],
		"EmbeddedObject": "{\"field\":\"Value with \\\"escaped quotes\\\"\"}"
	}
}

[edit] Features

  • Decode JSON-formatted strings into a usable data structure
  • Encode structured data into a JSON-formatted string
  • Interoperable with Dictionary and WWWForm
  • Optimized parse/stringify functions -- minimal (unavoidable) garbage creation
  • Asynchronous stringify function for serializing lots of data without frame drops
  • MaxDepth parsing will skip over nested data that you don't need
  • Special (non-compliant) "Baked" object type can store stringified data within parsed objects
  • Copy to new JSONObject
  • Merge with another JSONObject (experimental)
  • Random access (with [int] or [string])
  • ToString() returns JSON data with optional "pretty" flag to include newlines and tabs
  • Switch between double and float for numeric storage depending on level of precision needed (and to ensure that numbers are parsed/stringified correctly)
  • Supports Infinity and NaN values
  • JSONTemplates static class provides serialization functions for common classes like Vector3, Matrix4x4
  • Object pool implementation (experimental)
  • Handy JSONChecker window to test parsing on sample data

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 :)

Also, you JSON buffs (really, who would admit to being a JSON buff...) might also notice from my feature list that this thing isn't exactly to specifications. Here is where it differs:

  • "a string" is considered valid JSON. There is an optional "strict" parameter to the parser which will bomb out on such input, in case that matters to you.
  • The "Baked" mode is totally made up.
  • The "MaxDepth" parsing is totally made up.
  • NaN and Infinity aren't officially supported by JSON (read more about this issue... I lol'd @ the first comment on the first answer)
  • I have no idea about edge cases in my parsing strategy. I have been using this code for about 3 years now and have only had to modify the parser because other people's use cases (still valid JSON) didn't parse correctly. In my experience, anything that this code generates is parsed just fine.

[edit] Encoding

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.

Note: This section used to be WRONG! And now it's OLD! Will update later... this will all still work, but there are now a couple of ways to skin this cat.

//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.AddField("field1", 0.5);
//string
j.AddField("field2", "sampletext");
//array
JSONObject arr = new JSONObject(JSONObject.Type.ARRAY);
j.AddField("field3", arr);
 
arr.Add(1);
arr.Add(2);
arr.Add(3);
 
string encodedString = j.print();

NEW! The constructor, Add, and AddField functions now support a nested delegate structure. This is useful if you need to create a nested JSONObject in a single line. For example:

DoRequest(URL, new JSONObject(delegate(JSONObject request) {
	request.AddField("sort", delegate(JSONObject sort) {
		sort.AddField("_timestamp", "desc");
	});
	request.AddField("query", new JSONObject(delegate(JSONObject query) {
		query.AddField("match_all", JSONObject.obj);
	}));
	request.AddField("fields", delegate(JSONObject fields) {
		fields.Add("_timestamp");
	});
}).ToString());

[edit] Decoding

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".


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.b);
			break;
		case JSONObject.Type.NULL:
			Debug.Log("NULL");
			break;
 
	}
}

NEW! Decoding now also supports a delegate format which will automatically check if a field exists before processing the data, providing an optional parameter for an OnFieldNotFound response. For example:

new JSONObject(data);
list.GetField("hits", delegate(JSONObject hits) {
	hits.GetField("hits", delegate(JSONObject hits2) {
		foreach (JSONObject gameSession in hits2.list) {
			Debug.Log(gameSession);
		}
	});
}, delegate(string name) {	//"name" will be equal to the name of the missing field.  In this case, "hits"
	Debug.LogWarning("no game sessions");
});

[edit] Not So New! (O(n)) Random access!

I've added a string and int [] index to the class, so you can now retrieve data as such (from above):

JSONObject arr = obj["field3"];
Debug.log(arr[2].n);		//Should ouptut "3"

[edit] The Code

The code is now available on github.

[edit] Change Log

[edit] v1.4

Big update!

  • Better GC performance. Enough of that garbage!
    • Remaining culprits are internal garbage from StringBuilder.Append/AppendFormat, String.Substring, List.Add/GrowIfNeeded, Single.ToString
  • Added asynchronous Stringify function for serializing large amounts of data at runtime without frame drops
  • Added Baked type
  • Added MaxDepth to parsing function
  • Various cleanup refactors recommended by ReSharper

[edit] v1.3.2

  • Added support for NaN
  • Added strict mode to fail on purpose for improper formatting. Right now this just means that if the parse string doesn't start with [ or {, it will print a warning and return a null JO.
  • Changed infinity and NaN implementation to use float and double instead of Mathf
  • Handles empty objects/arrays better
  • Added a flag to print and ToString to turn on/off pretty print. The define on top is now an override to system-wide disable

[edit] Earlier Versions

I'll fill these in later...

Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Toolbox