Tel +49 (30) 814504070

Detlef Hüttemann
06.09.2006 06:45 Uhr

JSON and Rhino Pitfalls

Tags:

Using Rhino (serverside Javascript) will give you great possibilities when coding AJAX'ed webapps, since you can use cross-side Javascript libraries at both ends (server and browser).

Unfortunately the standard JSON.js lib won't work.

At the server side, the marschalling of JAVA-Objects will result in Stack Overflows; I assume this caused by infinite recursive .class lookups.

All you have to do to keep it running is to check wether your object is a pure JavaScript object or a JAVA object. In the case of JAVA-Objects, you cant't do anything except converting Strings to JavaScript Objects.

BTW: does anybody know why the Date marshalling is missing in JSON?

Take a look at the following source and add the bold-formatted line to your json.js ( strongly recomment the patched JSON (see comments at my last JSON blog post).

You can use any typical Java member or method to decide, wether the object is a plain JavaScript or a Java object. I decided to use the hashCode method.

You can download the modified JSON source here.

Example code snippet:

           object: function (x) {
                if (x) {

                    if (x instanceof Array) {
                        return s.array(x);
                    }
**                    if (x.hashCode) return s.string(''+x.toString());**

                    var a = ['{'], b, f, i, v;
                    for (i in x) {
                        v = x[i];
                        f = s[typeof v];
                        if (f) {

                            v = f(v);

                            if (typeof v == 'string') {
                                if (b) {
                                    a[a.length] = ',';
                                }
                                a.push(s.string(i), ':', v);
                                b = true;
                            }
                        }
                    }
                    a[a.length] = '}';
                    return a.join('');
                }
                return 'null';
            },


Bookmark and Share

Comments

About CosmoCode

CosmoCode is a Berlin based IT service provider with a strong emphasis on web applications. We mainly focus on Content Management Systems, Wikis and custom solutions.

Subscribe

Subscribe Like our blog? Stay up to date via RSS
Freie Stelle: Fachinformatiker Freie Stelle: Fachinformatiker