Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $ – ArrayList

Viewed 48

I am getting this error when clicking the button in my project and trying to print the data as text.

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

Can you help me with what I missed?

MainActivity:

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private val viewModel: PasswordGeneratorViewModel by viewModels()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.generatePassword.apply {
            setOnClickListener {
                binding.password.text = viewModel.responsePassword.toString()
            }
        }

    }

}

PasswordGeneratorViewModel:

@HiltViewModel
class PasswordGeneratorViewModel @Inject constructor(private val repository: PasswordGeneratorRepository): ViewModel() {

    private val _response = MutableLiveData<List<PasswordModel>>()
    val responsePassword: LiveData<List<PasswordModel>>
        get() = _response

    init {
        getPassword()
    }

    private fun getPassword() = viewModelScope.launch {
        repository.getPasswordGenerate().let {response ->
            if (response.isSuccessful){
                _response.postValue(response.body())
            }else{
                Log.d("tag", "getPassword Error: ${response.code()}")
            }
        }
    }

}

PasswordModel:

import com.google.gson.annotations.SerializedName

data class PasswordModel(
    @SerializedName("char")
    val char: List<String>
)
1 Answers

The response coming from the API is it not an array. The start of response indicates that it is an object. This is a sample output from that API:

{
"char": [
"ReaGU7]37tq"
   ]
}

Solution – use this:

class PasswordResponse : PasswordModel()

Related