I have an android application that relies heavily on Json Web Services.
so I have many requests and responses based on json format.
The basic idea is i have a request that get’s a bean object, for example HotelSearchData and the request knows how to convert that bean to json map\ object then it writes that JSONObject to the network (using http\https).
naturally I need to convert from and to json.
For the time being I’m doing it in a bad but fast way:
- get the
object - have a list of const in the form of
KEY_XXXXwherexxxxis the name of the key and the value is the string that will be the actual key in thejsonobject. - use the key like in the following example:
base.put(KEY_FROM_DATE, hotelSearchData.getFromDate()) - for ArrayList\ arrays I use
JSONArraynaturally, each{}injsonis a bean object as far as I’m concerned and I need to create a bean for it.
The problem is that this way, for future development is not so good (for the very least…)
Every new request requires me new beans that some of them may have the same information inside them causing information and code duplicity.
Every new request requires me to create new KEY finals copying sometimes from other request with similar keys – idiotic :-/
for the first item, except for optimizing what I’m about to do and dividing shared code beans to smaller items i can extend later on i can’t see any elegant solution.
But for the requests\response I thought of something but I’m not so sure how elegant it is…
I know Google have a different json library that uses reflection to serialize\deserialize JSONObjects. I thought of using annotations and reflection to do the serialization and deserialization, the annotations should help in the cases where the member name is NOT the same as the json key for the member’s value. also for ArrayList<?> that it’s type is not saved in byte code and so does not exist after compilation, so you can either specify basic type or full package name.
In this way once I create the bean with the help of some annotations (maybe python script \ant script to automate part of it ?) I can make beans that if tomorrow I move to xml or something else (binary) I can just create different serializer, deserializer and be done with it.
I hoped to hear your opinion on it, or some other solutions, get some inspiration, I’m really disappointed with my current code… 🙁
Have you actually tried gson? It will do the things you need, except the moving to XML/binary part, but you could probably abstract that in your code. Chances are that any XML serialization library might want to use different annotations, so it’s not going to be automatic.