JSON String Conversion object error: MorphDynaBean cannot be cast to com. softright. bean. testBean, the class has a set type attribute because JSONObject. toBean () converts a JSON string into a class defined by itself. When the attributes include List, Map, and ArrayList, the problem arises.
Error: MorphDynaBean cannot be cast to com. softright. bean. TestBean
Solution:
In JSONObject. toBean
If there is a set in the converted Class, you can first define Map <String, Class> classMap = new HashMap <String, Class> ();
Put in classMap the Set Name of the class you want to convert, such as: classMap. put ("data", StoDataInfo. class );
Of course, you can also put a collection class ("data", Map. class)
Add the parameter when toBean (), such as: ShenTongInfo stInfo = (ShenTongInfo) JSONObject. toBean (o, ShenTongInfo. class, classMap );
Specific instance
| The Code is as follows: |
Copy code |
|
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 {
Private Map <String, B> bMap = new HashMap <String, B> ();
Public (){}
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;
}
} |