How to Put and Get an Class Instance from Net. Sf. Json. Jsonobject

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)

1 Answer

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.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest