Using json-lib to transform to java throws ClassCastException

jeffery.yuan picture jeffery.yuan · May 14, 2011 · Viewed 7.5k times · Source

I am using json-lib to transform json object to java. The code is as below:

public class JsonConvertorDemo {

    public static void main(String[] args) {
        B b1 = new B("b1");
        Map<String, B> bMap = new HashMap<String, B>();
        bMap.put("key1", b1);
        A a1 = new A(bMap);

        JSONObject jsonObject = JSONObject.fromObject(a1);
        String json = jsonObject.toString();
        jsonObject = JSONObject.fromObject(json);

        Map<String, Class> classMap = new HashMap<String, Class>();
        classMap.put("bMap", Map.class);
        a1 = (A) JSONObject.toBean(jsonObject, A.class, classMap);

        bMap = a1.getbMap();
        System.out.println(bMap.get("key1").getB1());
    }
}

public class A {
    private Map<String, B> bMap = new HashMap<String, B>();
    public A() {}
    public A(Map<String, B> bMap) {
        this.bMap = bMap;
    }
    public Map<String, B> getbMap() {
        return bMap;
    }
    public void setbMap(Map<String, B> bMap) {
        this.bMap = bMap;
    }
}

public class B {
    private String b1;
    public B() {}
    public B(String b1) {
        this.b1 = b1;
    }
    public String getB1() {
        return b1;
    }
    public void setB1(String b1) {
        this.b1 = b1;
    }
}

It throws the following exception:

Exception in thread "main" java.lang.ClassCastException:
net.sf.ezmorph.bean.MorphDynaBean cannot be cast to code.orgexample.json.B
at code.orgexample.json.JsonConvertorDemo.main(JsonConvertorDemo.java:30)

Is there a way to specify class type of a map's value in json-lib?

Many thanks for any help.

Answer

chro picture chro · Jun 20, 2011

It's says here that fromObject accepts JSON formatted strings, Maps, DynaBeans and JavaBeans