Comparing Objects using JSON in AS3

I recently stumbled over a post on josh buhler’s blog regarding the comparison of two objects in AS3 using the ByteArray-class. u can read the post here.

this brought me to an idea..
instead of comparing each byte in a loop why not using a serialized string and a strict comparison ?

so here we go..

    import com.adobe.serialization.json.JSON;
    import com.adobe.serialization.json.JSONParseError;
    public class ObjectUtil {
     * class containing useful helper methods
     * @author  david linse (
     * @date  2009/21/08
     * compares given objects and returns boolean
     * result of compare action
     * @param obj1  object
     * @param obj2  object
     * @return  result  boolean true when identical; false otherwise
    static public function compare (obj1:Object, obj2:Object): Boolean {
      try {
  var value1: String = JSON.encode(obj1);
  var value2: String = JSON.encode(obj2);
      catch (e:JSONParseError) {
  trace('[ERROR] - '+ e.text);
  return false;
      return (value1 === value2);

this was the class, let’s go to a little usage sample..

  //-- an object and a reference to it
  var foo: Object = {label:"hi, i'am foo.."};
  var bar: Object = foo;, bar);    //-- result: true
  //-- two identical objects
  var foo1: Object = {label:"hi, i'am foo.."};
  var bar1: Object = {label:"hi, i'am foo.."};, bar1);    //-- result: true
  //-- two different objects
  var foo2: Object = {label:"hi, i'am foo.."};
  var bar2: Object = {label:"howdy, i'am bar.."};, bar2);    //-- result: false
  //-- or more complex objects
  var rect1:Rectangle = new Rectangle (0, 0, 100, 100);
  var rect2:Rectangle = new Rectangle (0, 0, 100, 100);, rect2);    //-- result: true
  //-- or more complex objects
  var rect3:Rectangle = new Rectangle (0, 0, 100, 100);
  var rect4:Rectangle = new Rectangle (0, 0, 100, 200);, rect4);    //-- result: false

works as expected..
what did you think ? feel free to use and reply as well.

This entry was posted in AS3, experiments and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">