Real Ultimate Programming

The Home for People Who Like to Flip Out and Write Code

Flexjson Hijinks

Flexjson has been good to me, but every once in a while it jumps up and surprises me. Here’s an example.

AbstractFoo.java

abstract class AbstractFoo {
    private Float a = 1.1f;
    private Float b = 2.2f;
    private Float c = 3.3f;

    public Float getA() {
        return a;
    }

    public Float getB() {
        return b;
    }

    public Float getC() {
        return c;
    }
}

Foo.java

import flexjson.JSONSerializer;

public final class Foo extends AbstractFoo {
        public static void main(final String[] args) {
                final Foo myFoo = new Foo();
                final JSONSerializer serializer = new JSONSerializer();
                System.out.println(serializer.serialize(myFoo));
        }
}

Can you guess what you’re going to get when you compile this and run java Foo? If you guessed:

{"a":1.1,"b":2.2,"c":3.3,"class":"Foo"}

you were wrong. You really get:

Exception in thread "main" flexjson.JSONException: Error trying to serialize path: [ a ]
        at flexjson.JSONSerializer$ObjectVisitor.bean(JSONSerializer.java:603)
        at flexjson.JSONSerializer$ObjectVisitor.json(JSONSerializer.java:471)
        at flexjson.JSONSerializer$ObjectVisitor.visit(JSONSerializer.java:435)
        at flexjson.JSONSerializer.serialize(JSONSerializer.java:222)
        at Foo.main(Foo.java:7)
Caused by: java.lang.IllegalAccessException: Class flexjson.JSONSerializer$ObjectVisitor can not access a member of class AbstractFoo with modifiers "public"
        at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:65)
        at java.lang.reflect.Method.invoke(Method.java:578)
        at flexjson.JSONSerializer$ObjectVisitor.bean(JSONSerializer.java:579)
        ... 4 more

It appears that Flexjson’s serialization algorithm can’t handle a package- visible, abstract super class. Changing it to public fixes the problem and you can continue on your merry way.

Back to flipping out…