JSON String Conversion object error: MorphDynaBean cannot be cast to com. softri

Source: Internet
Author: User

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;
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.