As well: Java.lang.classcastexception:org.json.jsonobject$null cannot be cast to Java.lang.Long
Reference: http://blog.csdn.net/u010823097/article/details/51780932
Problem:
In the process of using Java MongoDB Driver < version:3.2.2 >, the Updates method (MongoDB API Docs) can have a tricky problem.
such as set ("Data", UserData), when the UserData type is a collection in Java (for example, Jsonarray), the program throws Org.bson.codecs.configuration.CodecConfigurationException:Can ' t find a codec for class Jsonarray. Abnormal.
Solution:
This is because the basic data type for all operations of Mongodriver is Bson, and it does not have an inline method to convert Jsonarray to Bsonarray, which requires us to do the type conversion ourselves.
1 Questions: 2 3 in the process of using Java MongoDB Driver < version:3.2.2 > , the Updates method (MongoDB API Docs) can have a tricky problem. 4 such as set ("Data", UserData), when the UserData type is a collection in Java (for example, Jsonarray), the program throws Org.bson.codecs.configuration.Co Decconfigurationexception:can ' t find a codec for class Jsonarray. Abnormal. 5 6 7 Solution: 8 9 This is because the basic data type for all operations of Mongodriver is Bson, and it does not have an inline method to convert Jsonarray to Bsonarray, which requires us to do the type conversion ourselves.
The Bsonarray subtype is bsonvalue, and we need to convert the Java underlying type in Jsonarray to the Bsonvalue type, so I've customized a Bsontool.objecttobsonvalue () method:
1Jsonarray UserData =Jsonarray.parsearray (userdataobj);2Bsonarray Bsonarray =NewBsonarray ();3 jsonobject Jo;4 for(inti = 0; I < userdata.size (); i++) {5Jo =Userdata.getjsonobject (i);6Bsondocument document =Newbsondocument ();7 if(!Jo.isempty ()) {8Set<string> set =Jo.keyset ();9 for(String key:set) {Ten document.put (Key, Bsontool.objecttobsonvalue (Jo.get (key))); One } A } - Bsonarray.add (document); -}
The Bsonarray subtype is bsonvalue, and we need to convert the Java underlying type in Jsonarray to the Bsonvalue type, so I've customized a Bsontool.objecttobsonvalue () method:
1 Public classBsontool {2 3 /**4 * Java Object goto Bsonvalue Object5 * @paramobj6 * @return7 */8 Public Staticbsonvalue objecttobsonvalue (Object obj) {9 if(objinstanceofInteger) {Ten return NewBsonInt32 ((Integer) obj); One } A - if(objinstanceofString) { - return Newbsonstring ((String) obj); the } - - if(objinstanceofLong) { - return NewBsonInt64 ((Long) obj); + } - + if(objinstanceofDate) { A return NewBsondatetime ((Date) obj). GetTime ()); at } - return Newbsonnull (); - } - -}
In this tool class, the type is not covered completely, only the types I need are covered, and can be added as needed.
Finally just set ("Data", UserData) =>> set ("Data", Bsonarray), fix, error resolved.
Org.bson.codecs.configuration.CodecConfigurationException:Can ' t find a codec for class Org.json.jsonobject$null.