I am trying to create a JSONMessage class that can parse a json string and add the objects contained in the message to the List<T> t.
The object contained in the message implements the interface JSONSerialisation and implements the two methods toJSON() and fromJSON().
The code below does not work because I cannot instantiate the Type T and I get an error on the row t2.fromJSON... (as t2 has not been initialized).
I am not sure if my approach here is correct and if what I try to is achievable (create a generic JSONMessage) that I can use to encode/parse different type of objects. If that approach is not possible, I would appreciate hints of how I could achieve a similar result.
Regards
Interface
public interface JSONSerialisation {
public JSONObject toJSON();
public void fromJSON(JSONObject jsonObject);
}
Class
public class JSONMessage<T extends JSONSerialisation> {
private List<T> t;
public JSONMessage(String json) {
parseJSONMessage(json);
}
public void parseJSONMessage(String json) {
try {
this.t = new ArrayList<T>();
JSONObject jsonObject;
JSONArray lineItems;
jsonObject = new JSONObject(json);
this.messageHeader = new MessageHeader(jsonObject.getJSONObject("Header"));
lineItems = jsonObject.getJSONArray("Data");
int size = lineItems.length();
for (int i = 0; i < size; i++) {
T t2;
t2.fromJSON(lineItems.getJSONObject(i));
t.add(t2);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Looks like you are trying to replace the functionality available from most JSON deserialization libraries. You will notice that most of them require a parametized class, as a solution to the very problem you are facing. It’s not the most elegant solution, but it will work. I would drop the generic parameter from the deserialization class, and the stateful variables as well:
The code is obviously missing some error handling, and I made up a bogus
JSONElementtype in the enhanced for loop, but you get the general idea. Good luck.