I have 2 android apps - App A and App B. App A sends a JSON string via socket to App B. I have problems deserializing the JSON string on App B but I can deserialize it in App A. App A crashes when trying to run "gson.fromJson(json, mrlType)". (See code snippets below)

The error I received for deserializing it in App B is Expected BEGIN_ARRAY but was STRING at line 1 column 2 path $.

Things I have tried are:

  • I have tried to use DataOutputStream/DataInputStream and OutputStream/InputStream because I suspect it may have corrupted the JSON string which App A sent to App B.

  • I use GSON.toJson to create the JSON string and GSON.fromJson to deserialize the string.

  • I tried deserializing the same string that App A sent out to App B, on App A itself. It works like a charm.

  • I also encoded the byte array that JSON string was converted into, with UTF-8 before it was sent out by App A to App B. I converted it to String with this: String(buffer, Charsets.UTF-8) when App B received it.

// App A

var reminderList = getAllReminderInfoList()

val gson = Gson()
val jsonStr = gson.toJson(reminderList)

dataOutputStream.writeInt(bytes.size)
dataOutputStream.write(jsonStr.toByteArray(Charsets.UTF_8))
dataOutputStream.flush()

// App B

val len = dataInputStream.readInt()
buffer = ByteArray(len)
dataInputStream.readFully(buffer)
jsonStr = String(buffer, Charsets.UTF_8)

val gson = Gson()
val mrlType = object : TypeToken<ArrayList<MedicationReminderLine>>() {}.type
var list : ArrayList<MedicationReminderLine> = gson.fromJson(json, mrlType)

I really want App B to deserialize the json string with no issues. Apparently, it has nothing to do with programming logic (correct me if I am wrong). I think it has got to be some bug or characteristic of Gson that I am not familiar with. I really hope someone can point me in the right direction! Thanks.

0 Answers