I need to implement JSON serialization for some objects, and I've encountered a problem when it came to integration with generic collections.
All serializable classes implement this interface (JSONObject comes from this library):
interface JSONSerializable{ public JSONObject dump() throws JSONException //serializes object public void load(JSONObject obj) throws JSONException //deserializes object }
Code for my collection based on java.util.list looks more or less like this:
class AwesomeList<T extends JSONSerializable> implements JSONSerializable{ private LinkedList<T> items = new LinkedList<T>(); ... ... public JSONObject dump() throws JSONException { JSONObject result = new JSONObject(); JSONArray a = new JSONArray(); for(T i : items){ a.put(i.dump()); } result.put("items", a); return result; } public void load(JSONObject obj) throws JSONException{ //here is my problem } }
My problem is: When I load AwesomeList from JSONObject, I need to create its elements but it's impossible since java forbids me to write
T newItem = new T(); newItem.load(obj);
How should I modify my approach to this task?
The results show that Java serialization is slow for a small number of objects, but good for a large number of objects. Conversely, XML and JSON can outperform Java serialization for a small number of objects, but Java serialization is faster for a large number of objects.
Java serialization is slow because it uses reflection. JDK serialization does a lot of backward compatibility checking and strict type checking. But java serialization garneted 100% same object after deserialization in most of the case.
JSON-Java is a Java serialization/deserialization library. It parses JSON documents into Java objects and generates new JSON documents from the Java classes.
The main problem with Java Serialization is performance and efficiency. Java serialization is much slower than using in memory stores and tends to significantly expand the size of the object. Java Serialization also creates a lot of garbage.
Are you tied to this library? Google Gson is very popular. I have myself not used it with Generics but their front page says Gson considers support for Generics very important.
As others have hinted, you should consider dumping org.json's library. It's pretty much obsolete these days, and trying to work around its problems is waste of time.
But to specific question; type variable T just does not have any information to help you, as it is little more than compile-time information. Instead you need to pass actual class (as 'Class cls' argument), and you can then create an instance with 'cls.newInstance()'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With