Recently, when using JSON, the following error was reported:
Net.sf.ezmorph.bean.MorphDynaBean cannot is cast to java.lang.String
This error is common because JSON is converted to JavaBean by default to the Morphdynabean class. As in the following example:
When the JSON string is JavaBean, the general object can be transferred directly, such as: A student class, the attribute has the name, the age and so on.
Public classStudentImplementsjava.io.serializable{Private Static Final LongSerialversionuid = 1L; PrivateString sname; PrivateInteger age; PublicString Getsname () {returnsname; } Public voidsetsname (String sname) { This. sname =sname; } PublicInteger getage () {returnAge ; } Public voidsetage (Integer age) { This. Age =Age ; } }
You can use the following methods when you go to JavaBean by string:
String str = "[{\" sname\ ": \" admin\ ", \" age\ ": $}]" // receives the {} object, there is an exception to receive the array object, so you need to resolve the if (Str.indexof ("[")! = -1 = str.replace ("[", "); if (Str.indexof ("]")! = -1) { str = str.replace ("]", "" "); }jsonobject jobj = Jsonobject.fromobject (str); Student s = (Student) jsonobject.tobean (Jobj,student. Class );
This is not a problem, but if the property contains a complex type, when the property has a similar list, map,arraylist is not possible. Error: Morphdynabean cannot is cast to ******. In Jsonobject.tobean, if there is a collection in the converted class, you can define map Classmap = new HashMap (), and put the name of the collection in the Classmap class you want to convert, for example: Classmap.put (" Teachers ", Teacher.class), then add the parameters to the Tobean (), e.g. Student student= (Student) Jsonobject.tobean (str, Student.class, CLASSMAP);
Here is a small example:
Public classStudentImplementsjava.io.serializable{Private Static Final LongSerialversionuid = 1L; PrivateString sname; PrivateInteger age; PrivateList < String >courses; PublicString Getsname () {returnsname; } Public voidsetsname (String sname) { This. sname =sname; } PublicInteger getage () {returnAge ; } Public voidsetage (Integer age) { This. Age =Age ; } PublicList getcourses () {returncourses; } Public voidsetcourses (List courses) { This. courses =courses; } }
This is what you need to write when converting:
New HashMap (); Classmap.put ("courses", String. class = (Student) jsonobject.tobean (str, Student. Class, Classmap);
JSON Learning Series (5)-json Error Resolution Net.sf.ezmorph.bean.MorphDynaBean cannot is cast to