Unity Community

Register or Sign In:

+ Reply to Thread
Results 1 to 16 of 16

  1. Location
    Portland, OR
    Posts
    238

    MiniJSON script for parsing JSON data

    (Updated 12/1/11) It's the season for sharing.

    Attached is a handy script for encoding and decoding JSON data. This could be used as a way to pack arrays and dictionaries into PlayerPrefs, or a way to interact with web services.

    It's a small modification of a script I found online:
    http://techblog.procurios.nl/k/618/n...-for-JSON.html

    I modified it so that it would run in Unity iPhone without complaining or throwing exceptions.

    It can encode any basic type (int, string, float, etc.) and arrays, ArrayLists, and hashtables. Note: When you decode an array you always get an ArrayList back.

    There are a couple areas that I haven't tested throughly:
    * I haven't tried encoding and decoding Unicode text (above the normal ASCII range)
    * I haven't tried encoding and decoding numbers in a locale that uses . as the thousands seperator (1.234,56). I also haven't tried encoding numbers in one locale and decoding in another.

    Here's an example that gets tweets mentioning Unity3d:
    Code:  
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using MiniJSON;
    6.  
    7. public class MiniJsonDemo : MonoBehaviour {
    8.   void Start () {
    9.     StartCoroutine("GetTwitterUpdate");    
    10.   }
    11.  
    12.   IEnumerator GetTwitterUpdate() {
    13.     WWW www = new WWW("http://search.twitter.com/search.json?q=Unity3d");
    14.    
    15.     float elapsedTime = 0.0f;
    16.    
    17.     while (!www.isDone) {
    18.       elapsedTime += Time.deltaTime;
    19.      
    20.       if (elapsedTime >= 10.0f) break;
    21.      
    22.       yield return null;  
    23.     }
    24.    
    25.     if (!www.isDone || !string.IsNullOrEmpty(www.error)) {
    26.       Debug.LogError(string.Format("Fail Whale!\n{0}", www.error));
    27.       yield break;
    28.     }
    29.    
    30.     string response = www.text;
    31.    
    32.     Debug.Log(elapsedTime + " : " + response);    
    33.    
    34.     IDictionary search = (IDictionary) Json.Deserialize(response);
    35.    
    36.     IList tweets = (IList) search["results"];
    37.    
    38.     foreach (IDictionary tweet in tweets) {
    39.       Debug.Log(string.Format("tweet: {0} : {1}", tweet["from_user"], tweet["text"]));
    40.     }
    41.   }  
    42. }

    GitHub Gist: MiniJSON.cs

    For more complicated JSON serializing and deserializing, I highly recommend using JsonFX.
    JsonFX for Unity

    Edit: Updated and optimized this script to use generics and StringBuilders throughout. I've tested it with a ~32k JSON file, and it was able to serialize and deserialize it without issue. Added an MIT license header.
    Last edited by silentchujo; 12-01-2011 at 02:24 PM. Reason: Updated the script.


  2. Posts
    917
    Thanks! This should come in handy.
    Unity Pro + iPhone Advanced


  3. Location
    Land of wine & cheese
    Posts
    808
    Just a head's up on this MiniJSON; the class worked fine for minor things, but the moment i threw some modest-sized data at it on iOS, it caused the Garbage Collector to go nuts & the app to hang during the delay.

    Sometimes up to over a 1.5min, and that's not even with a big data set (40k or so).

    Your sharing this is still very much appreciated; just as a heads up, if you need to do heavy lifting with JSON, recommend instead JsonFx's Serialization library (http://jsonfx.net/download/).

    iOS friendly and MUCH faster w/out any major GC overhead.

    Thanks again!
    ByDesign Games
    Fresh Fun Games
    http://www.bydesigngames.com


  4. Location
    Zürich, Switzerland
    Posts
    25,088
    Will second the recommendation on JsonFX, definitely the most solid, iOS usable library (if you use Unity iOS 1.x, its actually the only one that works at all).
    It pushed through over 200 students each with about 2 dozen keys for a virtual master project expo guide earlier this year which were streamed from WWW upon request without any delay or GC spiking


  5. Posts
    78
    So JsonFX is more recommended over Litjson?


  6. Location
    Zürich, Switzerland
    Posts
    25,088
    With Unity iPhone 1.x Litjson just didn't work (but used it on a desktop project where its fine). It depends a bit on your requirements if its better or not


  7. Posts
    78
    Ahh, I guess I'll just try both then XD


  8. Location
    Land of wine & cheese
    Posts
    808
    Adding, had tried LitJSON prior to switching to JsonFX and found JsonFX more compatible for my purposes.
    ByDesign Games
    Fresh Fun Games
    http://www.bydesigngames.com


  9. Posts
    11
    Thank you, silentchujo! You saved my day


  10. Location
    Portland, OR
    Posts
    238
    bumping because I've cleaned up this script a bunch and added a link to a more Unity-friendly version of JsonFX.

    https://raw.github.com/gist/1411710/
    https://bitbucket.org/darktable/json...ty3d/downloads


  11. Location
    Virginia, USA
    Posts
    428
    That's cool, you're cool. I like JSON.
    Follow me @defjr


  12. Location
    Leamington Spa, UK
    Posts
    151
    Thanks for sharing :-)


  13. Posts
    1
    Can someone help me? I'm new to Json and I'm having trouble making the Json parsers work with this json string from the server I'm working on:

    [{"code":"200","message":"OK"},{"user_id":"1","face book_id":null,"user_name":"fendy","avatar_type":"1 4","level":"3","map_size":"1","credibility":"70 "}]

    I've tried DarkTable's JsonFx for Unity and MiniJson. My problem is always I get Invalid Cast Exception whenever I deserialize (in MiniJson's case, I do an explicit cast).

    I suspect that I might just be using these parsers wrong, unless the parsers themselves don't support the json string above.

    Can anyone show me how to deserialize the json string shown above? Whether it be MiniJson or JsonFx. I would appreciate it.


  14. Posts
    2
    Quote Originally Posted by Andrei_Nubee View Post
    Can someone help me? I'm new to Json and I'm having trouble making the Json parsers work with this json string from the server I'm working on:

    [{"code":"200","message":"OK"},{"user_id":"1","face book_id":null,"user_name":"fendy","avatar_type":"1 4","level":"3","map_size":"1","credibility":"70 "}]

    I've tried DarkTable's JsonFx for Unity and MiniJson. My problem is always I get Invalid Cast Exception whenever I deserialize (in MiniJson's case, I do an explicit cast).

    I suspect that I might just be using these parsers wrong, unless the parsers themselves don't support the json string above.

    Can anyone show me how to deserialize the json string shown above? Whether it be MiniJson or JsonFx. I would appreciate it.
    You have there two strings in request results.
    String 1: {"code":"200","message":"OK"}
    String 2 : {"user_id":"1","face book_id":null,"user_name":"fendy","avatar_type":"1 4","level":"3","map_size":"1","credibility":"70 "}

    So, you first need to iterate over an array of strings, and then, you must parse String2 (second element in string array) with the class that you have defined to represent it in your project.

    Take note that:
    All classes must have a simple constructor, without parameters.
    You can´t use Properties in C#, they throw an error in iOS


  15. Location
    Portland, OR
    Posts
    238
    Updated and fixed some bugs in MiniJSON.

    https://gist.github.com/1411710


  16. Location
    DFW, TX
    Posts
    584
    This MiniJSON stuff works great for me. Someone might find this useful:
    Code:  
    1.    public float GetAsFloat(object theObject, float defaultValue = 0.0f){
    2.         if(theObject == null){
    3.             return defaultValue;
    4.         }
    5.        
    6.         var newNumber = theObject.GetType().ToString() == "System.Double"?(double)theObject:(long)theObject;
    7.         return (float)newNumber;
    8.        
    9.     }

    If our db had float value of 1.0, I'd get a json object telling me the value is 1 (I think because php doesn't do types? I didn't code the backend part so I don't really know) -- this meant that when asking for a double, I'd sometimes get a long and it spit out an error. So the above code checks if it is null (if so, return default value) - if not null, it checks whether it's long or double before returning float.
    Last edited by JTown; 03-05-2012 at 04:35 PM.