Advantages of Parcelable over JSON - android

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.

Related

Android Intent passing parcelable object vs passing Json string

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...

Passing objects between activities in android why Parcelable ? why not JSON string?

I would like to know why object exchange between activities is made as Parcelable and why not as a JSON string. I understand Parcelable is better than Serialization. Can anyone make a comparison between Parcelable and JSON.
I would like to know why object exchange between activities is made as Parcelable and why not as a JSON string
Not everything that can go in a Parcel can go in a JSON string, such as:
IBinder objects (associated with remote services using AIDL)
ParcelFileDescriptor
Exception
Also, while you could convert a byte[] into a String (e.g., base-64 encoding), that will be inefficient.
Parcelable is very low level. Therefore its much faster then everything else available nowadays on android (like Serializeable). Json wouldn't make no sense regarding performance (think of performance issues while writing and reading json) and memory space.

Should I define one class for each REST JSON Request and Response?

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.

Benefits of GSON over normal JSON parse

The application I am working on is primarily based on manipulating JSON data obtained from the server. Traditional JSON parser extracts values, sets required POJOs and passes on to UI handler to render. This part is working well for now.
I have heard of GSON library and run through its implementation steps. As per my understanding, it (GSON usage) requires the following.
JSON data in proper syntax.
Model class objects matching JSON response.
GSON injector or code snippet to fetch JSON from the server and feeds to GSON.
The above approach sounds rather like object mapping. However, I am unaware about how efficient is GSON compared to old-fashioned JSON parsing; particularly with complex JSONs. And its implications on memory usage?
What do you think?
GSON has been successfully used in several android apps that are in Google Play today. The benefit you get with GSON is that object mapping can save the time spent writing code. As for the implications on memory usage, you can use the fromJson() method call that takes a streaming JSONReader to minimize the String data that is kept in memory, failing which you can try to parse the json data using a JSONReader yourself.
the GSON's goals is well described on official page:
Gson Goals:
Provide simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa
Allow pre-existing unmodifiable objects to be converted to and from JSON
Extensive support of Java Generics
Allow custom representations for objects
Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)
https://code.google.com/p/google-gson/

IntentService JSON to Object Conversion

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.

Categories

Resources