I am in the process of implementing an IntentService that I will use to perform RESTful web service calls, and then plan on using sendBroadcast to broadcast the results.
I receive JSON from the web service calls.
After I receive the JSON string, I'm not sure where I should actually parse the text and convert it into an object(s) (using GSON). Would I be better off making all my domain objects Parcelable, and send the objects in the broadcast, or just send the JSON text, and convert them when I actually need the objects? Any other advice?
Thanks.
It's a matter of personal preference, but I just write my own classes to serialize and deserialize between JSON strings and model objects. It might be a little bit of work to write the code as opposed to using some ORM like tool, but I find it to be very good for hunting down bugs or updating keys or nested hierarchies.
For each model object, I have a Translator class. For example Thing and ThingTranslator. This way, I can pass strings around between activities, and I have one single location where I can serialize and deserialize, so if there's ever anything wrong or something that needs to be updated (for ex, service changes object schema, etc) there's only one place to look.
Related
I am aware that there are some answers to my question, but the answers are not very elaborate or convincing.
In my program, in order to transmit data from one activity to another, I'm converting the contents of the POJO class into a Json String and passing via bundle (Method1).
METHOD1
String jsonString = JacksonSingleton.getObjectMapper().writeValueAsString(object);
bundle.putExtra(KEY_STR, jsonString)
In Method 2, I am passing a Parcelable object in the bundle.
METHOD2
bundle.putExtra(KEY_STR, parcelableObject);
If I were to implement Method 2, I'll have to implement Parcelable interface and write custom code for marshaling and unmarshaling my POJO class fields.
My question, which of these methods is better/recommended in terms of performance? Method 1 is very convenient but I want to follow best practices.
EDIT:
If you hate writing 'Parcelable' boilerplate code like me, you could use the Parcelable code generator plugin with your Android Studio/IntelliJ IDE. It will auto generate the methods for marshalling and unmarshalling your class fields. Very easy to use and highly recommended.
As much as I hate answering my own questions, I thought of sharing my observations that could help other developers in future.
Transmission of data from one activity to another can be done using either passing Serializable or Parcelable Objects in an activity intent. Android developer website recommends using Parcelable interface for this purpose.
However, my question was pertaining to the efficiency comparison between passing Parcelable object and JSON string.
To test this, I used an old and low-end Android device. I launched an activity by sending a large Parcelable Object in an activity intent. Next, I launched the same activity using the JSON String of the same object in the activity intent. What I observed was a significant observable latency while launching an activity by sending a JSON String instead of Parcelable Object.
In conclusion, even if we pass a JSON String, Java String object always implements Serializable. Google recommends using Parcelable instead of Serializable objects. This will usually be insignificant in case of strings of negligible length. However, in the case of massive Json Strings of massive objects, The efficiency will certainly take a toll.
You could refer this for performance benchmark of Parcelable vs Serializable.
TLDR:
Parcelable - More boilerplate code, better performance and a better engineering practice overall.
Serializable - Less code, easy to learn and acceptable if you're not obsessed with performance/best practices.
The JSON object/array is global usage, and can transfer over internet, we can handle it in the same way by different programming language on different platforms, and is easily stored. If the machine is not so slow and the data is not so huge, I prefer use JSON.
What for put extra with a large data to send to another activity? Sometimes I just send an ID for stored data or use a singleton to handle object... (Can another app access the Parcelable object?)
So the Parcelable is for cross process used in the same app.. Just like RemoteView and Service use it to transfer data for convenient...
In my android app, I need to post JSON data to several REST APIs and get JSON data back for parsing. I want to use GSON to serialize/deserialize the data.
Each REST API has different input/output fields, should I define a separate class to hold data for each API request and response like this?
public class API1RequestData{
public String field1;
public String field2;
}
I am asking this, because if I am using python to construct the JSON request, I don't need to define classes, a dictionary will do.
I believe you should by design (I end up re-using them when I can though). This guarantees you don't send unnecessary data to the server.
If you are really worried about data consumption, i recommend you to:
Do not send null values to the server (just check if they arrive null);
Use integers for errors in the response, instead of booleanor string
Send only new stuff when refreshing some data (save some checksum/timestamp of the "data version" and check it)
...
It all depends on what your application needs. Sometimes it's not worth adding some design patterns that will slow down development in exchange for nothing
I created a base class that has all of the functions for post and get, then I inherit that class and override the collection part of the class. Part of every request is authentication, request type, and request body. Part of every response is response type, permission level, and the data. The data becomes a collection on most of the inherited classes. This works well for serialization and deserialization on both ends and using the base class keeps code maintenance to a minimum.
I've had other projects where I've done things differently for various reasons. Whatever works is good. If you have identically structured requests but the names are what is different, then just make one class and rely on context to know what it is. If the requests are structured differently, use different classes.
I want to pass a user defined data type(a complex data type- an object say) to asmx web service from my android app. I have tried of sending primitive data
types and works fine. When I am trying to send the object it self as it is then I got the following error. (See link below)
http://pastie.org/5935960
and here is the code I am using to call the web service http://pastie.org/5936733
and this is my class Implementation http://pastie.org/5936414 and
another class implementation is here http://pastie.org/5936586.
Note: Every thing works fine when I send the data with primitive data types but when I send the data with my class object it is throwing an exception.
Please any onc could try to tell me what may be the problem. I was on this problem for last 4 days but could not resolve it still.
Thanks
Ganesh
You need a way to serialize/write your data so that it can be parsed and converted back to objects on the receiving side (asmx web service).
Popular approaches are to use JSON/XML for text based solutions i.e. human readable. There are also solutions for serializing the data to binary. I only have experience with Google protocol buffers, which worked quite well for me.
For the JSON approach you basically have a read and write method in each class you wish to transfer. These methods are used to convert your object to and from your desired format (JSON/XML).
Hope that helps.
I'm currently using JSON (org.json) to serialize one of my data classes. When I pass it in a Bundle or with an Intent, I just call .toString() on the sender side and then recreate the class on the receiving side. From everything I've read so far, I should not implement Java's Serializable due to performance concerns. I'm in the process of rewriting certain portions of the app and I was considering making my data classes implement Parcelable and transfer them that way. What would the advantages be if I did it that way? Would it be preferable if I used the Jackson JSON library instead? Most of the JSON work is based on the API; server responds only with JSON. I also store some of the JSON for caching on the app side.
I think JSON is by far the most convenient mechanism for typical POJOs; and it seems unlikely that performance should be significantly worse that with Parcelable. Parcelable implementation could be more compact; but if that is problematic, you could even compress cached JSON payloads. So I would probably try out JSON first and see how it works.
I have a REST API which returns JSON to its calls. However, depending on the call I perform, the answer varies. Using Gson will result in a different POJO object for each API response.
Considering I have an IntentService who handles all my GET requests, and I only pass it an URL in the intent, what would be the best way to handle the different responses in the IntentService?
I've been messing around with JSONs in Android for a while, but I can't seem to find an elegant/smart solution for this issue. I've been creating an enum to differentiate the possible API requests, and passing the selected enum value in the intent, in order for the IntentService to choose the action to perform using a switch statement.
Thank you.
If there is a common business logic for all the resulting different POJOs you get, then it would be nice to try to use the same Class, and for this, to try to customize the GSON mapping strategy.
If you don't really have a common logic, then you can consider your GSON objects as DTOs, and then your "mapping" to the business Classes is done on a lower layer (And you have here a lot of ways to do it, including Dozer).
For a more specific answer, more details or examples for your project would help.