parentLoader == null && !nullAllowed Or Expected BEGIN_OBJECT – Gson Android

Hello Friends,

While parsing JSON or JSONArray using Gson library if you are facing issues like

  • parentLoader == null && !nullAllowed
  • java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

Then don’t worry here is the perfect solution to get rid of these exceptions.

Consider below example where I want to parse below JSONArray using Gson library

[
    {
        "nid": "139",
        "title1": "complaint",
        "purchase_id": "138",
        "device_id": "23",
        "device_unit_id": "27",
        "node_field_data_field_purchase_client_nid": "21",
        "field_engineer_location": "Mumbai",
        "field_engineer_email": "nikhil.lotke88@gmail.com",
        "device_serial_no": "9025521-2",
        "field_complaint_id": "",
        "field_complaint_status": "open",
        "field_complaint_type": "Technical Service",
        "field_start_time": "2018-11-03 18:30:30",
        "field_closure_time": "2018-11-03 18:30:30",
        "field_complaint_description": "Test is the field",
        "field_article_code": "254478888656989",
        "field_client_location": "Chennai"
    }
]

then my approach should be: ✔

MComplaintDetails[] mComplaintDetails = new Gson().fromJson((String)myAboveJsonArray, MComplaintDetails[].class);

Instead of ✖

MComplaintDetails mComplaintDetails = new Gson().fromJson((String)myAboveJsonArray, MComplaintDetails.class)

Or ✖

MComplaintDetails mComplaintDetails = new Gson().fromJson((String)myAboveJsonArray, new TypeToken<List<MComplaintType>>() {}.getType())

 

Leave a Reply

Be the First to Comment!

avatar
  Subscribe  
Notify of