Kotlin – Unable to parse JSON Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Kotlin – Unable to parse JSON without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am trying to parse a JSON using Kotlin (I’m new to Kotlin / Android) and I can’t seem to find a way to get it done.

[{
    "submission_date": "March 2018",
    "user_answers": [{
        "question_id": 0,
        "answer": 5
    }, {
        "question_id": 1,
        "answer": 5
    }]
}, {
    "submission_date": "March 2018",
    "user_answers": [{
        "question_id": 0,
        "answer": 0
    }, {
        "question_id": 1,
        "answer": 0
    }]
}]

After trying for some time with Klaxon I decided to give GSON a try and start following this: https://www.youtube.com/watch?v=53BsyxwSBJk

The code seems pretty straight forward:

val gson = GsonBuilder().create()
val userSessions = gson.fromJson(userDataJSON, UserSession::class.java)

Here are the models:

class UserSession(submissionDate : String)
{
    var submissionDate : String
    var userAnswers : ArrayList<UserAnswer> = ArrayList<UserAnswer>()

    init
    {
        this.submissionDate = submissionDate
    }

    // We call this function later on, when we have a UserAnswer array  to work with
    fun addArray(userAnswersArray : ArrayList<UserAnswer>)
    {
        if(userAnswersArray.size > 0)
        {
            for (userAnswer : UserAnswer in userAnswersArray)
            {
                this.userAnswers.add(userAnswer)
            }
        }
        else
        {
            println("No user answer found. Array is empty.")
        }
    }
}

class UserAnswer(idQuestion : Int, userAnswer : Int)
{
    var idQuestion : Int
    var userAnswer : Int

    init
    {
        this.idQuestion = idQuestion
        this.userAnswer = userAnswer
    }
}

However, I get JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $ As far as I’m aware, the JSON is valid, or so JSONLint says.

Any ideas? I’ve been struggling for some time with parsing this JSON without any luck.

Answer

there is problem with variable name as you are going to map your json directly into pojo (model) class with gson. always json key name and model variable name should be same while working with gson.

changes should like this :

  • json should be same as showing

  • change variable type in models :

    var submission_date : String

    var user_answers : ArrayList = ArrayList()

    var question_id : Int

    var answer : Int

change all getter / setter and methods according to these variable name

this will works..

We are here to answer your question about Kotlin – Unable to parse JSON - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji