Как заставить GSON & Retrofit сериализовать и отобразить массив из ответа JSON в строку? - PullRequest
0 голосов
/ 13 октября 2018

Я делаю запрос API, который возвращает некоторые значения массива.Мне нужно сериализовать эти значения массива, чтобы я мог назначить их соответствующим атрибутам класса (которые являются типами String).

Теперь я знаю, как использовать GSON для сериализации и десериализации списков, но с помощью Retrofit отображение выполняется автоматически.Это означает, что если мой атрибут имеет тип String, вызов API возвращает ошибку «Ожидается строка, но вместо этого получен массив».Как мне обойти это, чтобы я мог получать их как массивы без сбоев, и они впоследствии сохраняли их как строки?

Мой ответ API:

{
"utterances": [{
        "langs": ["eng", "afr", "xho", "zul"],
        "utts": [
            "Have you been here before?",
            "Was u al hier gewees?",
            "Ingaba wakhe weza apha ngaphambili?",
            "Ingabe uke weza lapha ngaphambilini?"
        ],
        "responses": [
            ["Yes", "No"],
            ["Ja", "Nee"],
            ["Ewe", "Hayi"],
            ["Yebo", "Cha"]
        ]
    },
    {
        "langs": ["eng", "afr", "xho", "zul"],
        "utts": [
            "How are you?",
            "Hoe gaan dit met jou?",
            "unjani?",
            "unjani?"
        ],
        "responses": [
            ["Good", "Bad"],
            ["Goed", "sleg"],
            ["ezilungileyo", "ezimbi"],
            ["kuhle", "kubi"]
        ]
    }
]
}

Мой класс UtteranceResponse:

class UtteranceResponse {

@SerializedName("status")
var status: String? = null

@SerializedName("count")
var count: Int = 0

@SerializedName("utterances")
var utterances: ArrayList<Utterance>? = null
}

Мой класс произнесения:

class Utterance: SugarRecord {

@SerializedName ("langs")
var langs: String? = null

@SerializedName ("utts")
var utterances_text: String? = null

var utterances_tts: String? = null

@SerializedName ("responses")
var responses_text: String? = null

constructor(){

}
}

И, наконец, вызывающая функция:

    fun getUtterancesFromWebservice (){
    val apiService = ApiInterface.create()
    val call = apiService.getUtteranceDetails()

    call.enqueue(object: Callback<UtteranceResponse> {
        override fun onResponse(call: Call<UtteranceResponse>, response: retrofit2.Response<UtteranceResponse>?) {
            if (response != null) {
                if (response.body()?.utterances != null){
                    var list: List<Utterance> = response.body()?.utterances!!
                    val utterances: Utterance = list[0]
                    //storeUtterancesFromList(list)
                } else {
                    Log.d ("Response:", response.body().toString())
                }
            }else{
                Log.d ("responseResult", "NULL")
            }

        }

        override fun onFailure(call: Call<UtteranceResponse>, t: Throwable) {
            Log.e("SHIT", t.toString())

        }
    })
}

ОБНОВЛЕНИЕ Мой интерфейс API:

@GET("bins/1ahazo")
abstract fun getUtteranceDetails():Call<UtteranceResponse>

    companion object Factory {
        const val BASE_URL = "https://api.myjson.com/"
        fun create(): ApiInterface {
            val gson = GsonBuilder().setPrettyPrinting().create()
            val retrofit = Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build()
            return retrofit.create(ApiInterface::class.java)
        }
    }

1 Ответ

0 голосов
/ 13 октября 2018

Вы возвращаете один объект, а не список.Измените Call<UtteranceResponse> в ApiInterface на

Call<List<Utterance>>

и для преобразования списка в строку список в строку и строку в список

class Utterance: SugarRecord {

@SerializedName ("langs")
var langs: List<String?>? = null 

@SerializedName ("utts")
var utterances_text: String? = null

var utterances_tts: List<String?>? = null

@SerializedName ("responses")
var responses_tex:List<List<String?>?>? = null;

constructor(){

 }
}
...