2017-06-19 58 views
-6

我在Kotlin中有这个JSON,我无法获取和解析。任何快速帮助。请。Kotlin Json解析器

[{platform: {name: "mena-web",publishingRegion: "mena",platformGroup:"web",id: 2,countryCode: "AE",locales: {locale:["en_US","ar_AE"]}}}] 

这里是我的数据类:

data class Locales(var locale: ArrayList<String>) {} 

data class Platform(var name: String, var publishingRegion: String, var platformGroup: String, var id: Int, var countryCode: String, var locales: Locales) {} 

data class Json(var platform: Platform) {} 

这里是我的JSON API接口:

interface Api { 
    @GET("/me.json2") 
    fun getGeo(callback: Callback<List<Json>>): Call<List<Json>> 
} 

这里是我的RESTAPI:

class RestAPI(val api: Api) { 

    fun getNews(callback: Callback<List<Json>>) { 
     val call = api.getGeo(callback) 
     call.enqueue(callback) 
    } 
} 

这里是我的RESTAPI请致电:

try { 
    val api: RestAPI 
    val retrofit = Retrofit.Builder() 
         .baseUrl(PLATEFORM_URL) 
         .addConverterFactory(MoshiConverterFactory.create()) 
         .build() 

    api = retrofit.create(RestApi::class.java) 
    val callback = object : Callback<List<Json>> { 

     override fun onResponse(call: Call<List<Json>>?, response: retrofit2.Response<List<Json>>?) { 
      response?.isSuccessful.let { 
       [email protected] = response?.body() 
      } 
     } 

     override fun onFailure(call: Call<List<Json>>?, t: Throwable?) { 
      Log.e("MainActivity", "Problems calling API", t) 
     } 

    } 

    api.getGeo(callback) 
// Log.e("Message", test.getNews().toList().toString()) 
} catch(e:Exception){ 
    Log.e("Message", e.message) 
} 
+3

什么是你所得到的错误字符串?如果可能,请发布堆栈跟踪。 –

+0

你正在使用哪个解析器? –

+0

@ Miha_x64他使用Moshi,查看最后一段代码片段:'.addConverterFactory(MoshiConverterFactory.create())' –

回答

0

谢谢! 我找到了答案,更改解析器后的所有数据工作

MoshiConverterFactory to GsonConverterFactory。

0

阶跃响应是,这将是你的jsonResponse

try { 
val rootArray = JSONArray(respones) 
val mainObject=rootArray.getJSONObject(0) 
val platformObject=mainObject.getJSONObject("platform") 
val name=platformObject.getString("name") 
val publishingRegion=platformObject.getString("publishingRegion") 
val platformGroup=platformObject.getString("platformGroup") 
val id=platformObject.getInt("id") 
val countryCode=platformObject.getString("countryCode") 
val localesObj=platformObject.getJSONObject("locales") 
val localeArray=locales.getJSONArray("locale") 
val stringOne=localeArray.getString(0) 
val stringTwo=localeArray.getString(1) 
} catch (e: JSONException){}