Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

changed extended (mini)JSON class by WyrmTale

Discussion in 'Scripting' started by mas, Apr 9, 2013.

  1. mas

    mas

    Joined:
    Nov 14, 2010
    Posts:
    696
    Because I am working on a CouchDB class ( to be released at a later stage in the Asset Store | Free ) to manage data streams to and from CouchDB databases and Services like Cloudant, I have been searching for a good (and simple) JSON parser and formatter.

    Most .NET libs I encountered were a bit buggy, fatty or complex to use.

    I encountered and really liked MiniJSON by Darktable ( Calvin Rien | https://gist.github.com/darktable/1411710 ). Its simple and you have total control.

    However ..

    I found that i lacked some functionality, hence the JSON class I present to you ...
    ( and licensed under the open source MIT License )

    Download the WyrmTale JSON class unit here : View attachment $JSON.cs

    Based on MiniJSON, its got :

    • access to JSON as an object instead of a static class
    • using class indexers to set data
    • supporting some unity types like Vector2, Vector3, Rect, Color, Color and Color32
    • simple way to support/extend to you own custom classes

    Some usage example code

    Formatting JSON from basic and unity types.
    Code (csharp):
    1.  
    2.         JSON js = new JSON();      
    3.         // ----------------------------------------------
    4.         // base types
    5.         // string
    6.         // ----------------------------------------------
    7.         js["myString"] = "This is a string ";
    8.         js["myStringArray"] = new string[] {"string value 1","string value 2", "string value 3"};
    9.         // int
    10.         js["myInt"] = 1234;
    11.         js["myIntArray"] = new int[] {1,2,3};
    12.         // float
    13.         js["myFloat"] = 0.5f;
    14.         js["myFloatArray"] = new float[] {1.5f,2.5f,3.5f};
    15.         // boolean
    16.         js["myBoolean"] = true;
    17.         js["myBooleanArray"] = new bool[] {true, false, true};
    18.         // ----------------------------------------------
    19.         // Supported Unity Types
    20.         // ----------------------------------------------
    21.         // Vector2
    22.         js["myVector2"] = (JSON)(new Vector2(100.5f,123.45f));
    23.         js["myVector2Array"] = new JSON[] {
    24.             (JSON)(new Vector2(100.5f,123.45f)),
    25.             (JSON)(new Vector2(200.5f,234.45f)),
    26.             (JSON)(new Vector2(300.5f,345.45f))
    27.         };
    28.         // Other supported Unity classes
    29.         js["myVector3"] = (JSON)Vector3.one;
    30.         js["myRect"] = (JSON)(new Rect(10,10,100,200));
    31.         js["myColor"] = (JSON)Color.cyan;
    32.         js["myColor32"] = (JSON)(new Color32(245,210,155,128));
    33.         js["myQuaternion"] = (JSON)Quaternion.identity;
    34.                    
    35.         // Get serialized JSON string
    36.         string jsonString = js.serialized;
    37.         //  {
    38.         //      "myString":"This is a string ",
    39.         //      "myStringArray":["string value 1","string value 2","string value 3"],
    40.         //      "myInt":1234,"myIntArray":[1,2,3],
    41.         //      "myFloat":0.5,
    42.         //      "myFloatArray":[1.5,2.5,3.5],
    43.         //      "myBoolean":true,
    44.         //      "myBooleanArray":[true,false,true],
    45.         //      "myVector2":{"x":100.5,"y":123.45},
    46.         //      "myVector2Array":[{"x":100.5,"y":123.45},{"x":200.5,"y":234.45},{"x":300.5,"y":345.45}],
    47.         //      "myVector3":{"x":1,"y":1,"z":1},
    48.         //      "myRect":{"left":10,"top":210,"width":100,"height":200},
    49.         //      "myColor":{"r":0,"g":1,"b":1,"a":1},
    50.         //      "myColor32":{"r":245,"g":210,"b":155,"a":128},
    51.         //      "myQuaternion":{"x":0,"y":0,"z":0,"w":1}
    52.         //  }  
    Parsing JSON and getting it to your variables
    Code (csharp):
    1.  
    2.         js = new JSON();
    3.         // Parse JSON string
    4.         js.serialized = jsonString;
    5.         // ----------------------------------------------
    6.         // base types
    7.         // ----------------------------------------------
    8.         // get string and string[]
    9.         string myString = js.ToString("myString");
    10.         string[] myStringArray = js.ToArray<string>("myStringArray");
    11.         // get int and int[]
    12.         int myInt = js.ToInt("myInt");
    13.         int[] myIntArray = js.ToArray<int>("myIntArray");
    14.         // get float and float[]
    15.         float myFloat = js.ToFloat("myFloat");
    16.         float[] myFloatArray = js.ToArray<float>("myFloatArray");
    17.         // get bool and bool[]
    18.         bool myBoolean = js.ToBoolean("myBoolean");
    19.         bool[] myBooleanArray = js.ToArray<bool>("myBooleanArray");
    20.        
    21.         // ----------------------------------------------
    22.         // Supported Unity Types
    23.         // ----------------------------------------------
    24.         // get Vector2 and Vector2[]
    25.         Vector2 myVector2 = (Vector2)js.ToJSON("myVector2");
    26.         Vector2[] myVector2Array = js.ToArray<Vector2>("myVector2Array");
    27.         // get other Unity types
    28.         Vector2 myVector3 = (Vector3)js.ToJSON("myVector3");
    29.         Rect myRect = (Rect)js.ToJSON("myRect");
    30.         Color myColor = (Color)js.ToJSON("myColor");
    31.         Color32 myColor32 = (Color32)js.ToJSON("myColor32");       
    32.         Quaternion myQuaternion = (Quaternion)js.ToJSON("myQuaternion");
    33.  
    By adding 3 methods to your custom classes you can simply support formatting to and parsing from JSON

    • static implicit operator to format to JSON
    • static explicit operator to parse JSON to you custom class
    • static Array() method to convert an JSON[] object array to an array with your class elements

    The Example class
    Code (csharp):
    1.  
    2. public class MyClass
    3. {
    4.     public GameObject gameObject;  
    5.    
    6.     // constructor will create an 'empty' game object
    7.     public MyClass(string name, Vector3 position, Vector3 localScale, Quaternion rotation)
    8.     {
    9.         this.gameObject = new GameObject(name);
    10.         this.gameObject.transform.position = position;
    11.         this.gameObject.transform.localScale = localScale;
    12.         this.gameObject.transform.rotation = rotation;
    13.     }
    14.  
    15.     // serialize this class to JSON
    16.     public static implicit operator JSON(MyClass value)
    17.     {
    18.         GameObject g = value.gameObject;
    19.         JSON js = new JSON();
    20.         if (g!=null)
    21.         {
    22.             JSON jsTransform = new JSON();
    23.             js["name"] = g.name;
    24.             js["transform"] = jsTransform;
    25.             jsTransform["position"] = (JSON)g.transform.position;
    26.             jsTransform["localScale"] = (JSON)g.transform.localScale;
    27.             jsTransform["rotation"] = (JSON)g.transform.rotation;
    28.         }          
    29.         return js;
    30.     }              
    31.    
    32.     // JSON to class conversion
    33.     public static explicit operator MyClass(JSON value)
    34.     {
    35.         checked
    36.         {
    37.             JSON jsTransform = value.ToJSON("transform");          
    38.             return new MyClass(
    39.                 value.ToString("name"),
    40.                 (Vector3)jsTransform.ToJSON("position"),
    41.                 (Vector3)jsTransform.ToJSON("localScale"),
    42.                 (Quaternion)jsTransform.ToJSON("rotation"));
    43.         }
    44.    }               
    45.    
    46.    // convert a JSON array to a MyClass Array
    47.    public static MyClass[] Array(JSON[] array)
    48.    {
    49.         List<MyClass> tc = new List<MyClass>();
    50.         for (int i=0; i<array.Length; i++)
    51.             tc.Add((MyClass)array[i]);
    52.         return tc.ToArray();
    53.    }               
    54. }
    55.  
    To format this custom class and an array with classes to JSON
    Code (csharp):
    1.  
    2.         js = new JSON();
    3.         // ----------------------------------------------
    4.         // custom type | MyClass to store gameobject name + transform
    5.         // ----------------------------------------------
    6.         js["mainObject"] = (JSON)(new MyClass("main",
    7.             new Vector3(10,10,10), new Vector3(1,1,1), Quaternion.identity));
    8.         js["ObjectArray"] = new JSON[] {
    9.             (JSON)(new MyClass("object.1",
    10.             new Vector3(20,20,20), new Vector3(2,2,2), Quaternion.identity)),
    11.             (JSON)(new MyClass("object.2",
    12.             new Vector3(30,30,30), new Vector3(3,3,3), Quaternion.identity)),
    13.             (JSON)(new MyClass("object.3",
    14.             new Vector3(40,40,40), new Vector3(4,4,4), Quaternion.identity))};
    15.        
    16.         jsonString = js.serialized;
    17.         // {
    18.         //      "mainObject": {
    19.         //          "name":"main",
    20.         //          "transform":{
    21.         //              "position":{"x":10,"y":10,"z":10},
    22.         //              "localScale":{"x":1,"y":1,"z":1},
    23.         //              "rotation":{"x":0,"y":0,"z":0,"w":1}
    24.         //          }
    25.         //      },
    26.         //      "ObjectArray":[
    27.         //          {   "name":"object.1",
    28.         //              "transform":{
    29.         //                  "position":{"x":20,"y":20,"z":20},
    30.         //                  "localScale":{"x":2,"y":2,"z":2},
    31.         //                  "rotation":{"x":0,"y":0,"z":0,"w":1}
    32.         //              }
    33.         //          },{ "name":"object.2",
    34.         //              "transform":{
    35.         //                  "position":{"x":30,"y":30,"z":30},
    36.         //                  "localScale":{"x":3,"y":3,"z":3},
    37.         //                  "rotation":{"x":0,"y":0,"z":0,"w":1}
    38.         //              }
    39.         //          },{ "name":"object.3",
    40.         //              "transform":{
    41.         //                  "position":{"x":40,"y":40,"z":40},
    42.         //                  "localScale":{"x":4,"y":4,"z":4},
    43.         //                  "rotation":{"x":0,"y":0,"z":0,"w":1}
    44.         //          }
    45.         //      }]
    46.         //  }
    47.  
    48.  
    To parse the JSON string, created above , back to 'new' objects ( because MyClass is coded that way )
    Code (csharp):
    1.  
    2.         js = new JSON();
    3.         js.serialized = jsonString;
    4.        
    5.         MyClass mc = (MyClass)js.ToJSON("mainObject");
    6.         MyClass[] mcArray = MyClass.Array(js.ToArray<JSON>("ObjectArray"));
    7.  
    Download the WyrmTale JSON class unit here : View attachment $JSON.cs
    ( and licensed under the open source MIT License )

    Cheers!
     
    Last edited: Apr 9, 2013
  2. DennisVH

    DennisVH

    Joined:
    Jul 8, 2012
    Posts:
    48
    Wow! Awesome!
     
  3. wccrawford

    wccrawford

    Joined:
    Sep 30, 2011
    Posts:
    2,039
    Might want to note in the first post that it's MIT licensed since people won't know that unless they download it, and most will just go find something else instead, assuming you didn't bother to give it a license, which would make it useless to them.
     
  4. mas

    mas

    Joined:
    Nov 14, 2010
    Posts:
    696
    Good suggestion .. forgot about that .. I have put it in the first post.