androidgsonparcelable

Gson.toJson(PrinterInfo) returns empty object


I'm trying to serialize an android.print.PrinterInfo object to JSON using Gson (version 2.9.0):

val type: Class<*> = data.javaClass
json.beginObject()
json.name(type.name)
json.value(gson.toJson(data, type))
Log.d(TAG, data.toString())
json.endObject()

but the result is an empty object {android.print.PrinterInfo: {}}. The log line clearly shows that the object is populated, there are no null values or similar (but using GsonBuilder() to include nulls, to pretty print or anything else doesn't make any difference). There are no exceptions, just no expected result.


Solution

  • The main problem seems to be that you are trying to serialize a class from the Android library without using a custom Gson adapter for this. In that case Gson will use reflection to access the fields of the class, including private fields which represent implementation details.

    Even if this worked and you got a non-empty JSON object, it would contain internal data of the class, so it might differ between Android versions (maybe even between different Android devices?). And there is no guarantee that you can properly recreate a PrinterInfo object using Gson.fromJson this way. Possibly the PrinterInfo you would receive is in an inconsistent state and non-functional.

    A better solution here would be either to write a custom Gson TypeAdapter for the PrinterInfo class (and referenced classes) which performs the serialization (and deserialization).
    Or because PrinterInfo implements Parcelable another option might be to use its writeToParcel method instead of serializing it as JSON.

    In the future you can also use Gson's ReflectionAccessFilter to avoid depending on reflection-based serialization of Android library classes by accident.


    Arguably this does not answer why the JSON object in your question is empty, but it highlights that trying to (implicitly) use reflection for JSON serialization of third-party classes has its disadvantages, and that there are other alternatives.