I am using net.sf.json package for handling json. I have a Class named CustomerClass. I want to store an instance of this class in a JSON Object and retrieve the class instance later.
My Code :
import net.sf.json.JSONObject;
class Test {
JSONObject test = new JSONObject;
CustomerClass obj = new CustomerClass();
test.put("objInstance", (Object) obj);
CustomerClass retrievedInstance = (CustomerClass) test.get("objInstance"); // throws the error
}
Error Thrown
java.lang.ClassCastException: class net.sf.json.JSONObject cannot be cast to class
com.CustomerClass (net.sf.json.JSONObject and
com.CustomerClass are in unnamed module of loader
org.apache.catalina.loader.ParallelWebappClassLoader @18245eb0)
CodePudding user response:
According to the javadocs of JSONObject here,
The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or the JSONNull object
So basically you cannot put any object it JSONObject and retrieve it later. If I try it will put {}
.
public class CustomerClass {
public CustomerClass(String string, String string2) {
name = string;
id=string2;
}
String name;
String id;
}
JSONObject test = new JSONObject();
CustomerClass obj = new CustomerClass("Hello", "Hi");
String testStr = "Hi";
test.put("objInstance", (Object)obj);
test.put("str", testStr);
Object retrievedInstance = test.get("objInstance"); // throws the error
String retrivedStr = (String)test.get("str");
System.out.println(retrivedStr);
System.out.println(retrievedInstance);
System.out.println(test);
Output:
Hi
{}
{"objInstance":{},"str":"Hi"}
So way out is you can use GSON library to map your Class CustomerClass to JSONObject and retrieve it later. Read this.