Kotlin convert json array to model list using GSON

后端 未结 3 725
一个人的身影
一个人的身影 2021-02-13 05:15

I am not able to convert a JSON Array into a GroupModel array. Below is the JSON I used:

[{
  \"description\":\"My expense to others\",
  \"items\"         


        
相关标签:
3条回答
  • 2021-02-13 05:33
    [{
      "description":"My expense to others",
      "items":["aaa","bbb"],
      "name":"My Expense"
     },
     {
      "description":"My expense to others","
      items":["aaa","bbb"],
      "name":"My Expense"
     }]
    

    Kotlin Code

    val gson = GsonBuilder().create()
    val Model= gson.fromJson(body,Array<GroupModel>::class.java).toList()
    

    Gradle

    implementation 'com.google.code.gson:gson:2.8.5'
    
    0 讨论(0)
  • 2021-02-13 05:37

    You need to use a TypeToken to capture the generic type of the array, and you need this to be the type that GSON sees as the target, instead of just GroupModel::class it is really a list of those. You can create a TypeToken and use it as follows:

    Type groupListType = new TypeToken<ArrayList<GroupModel>>() {}.getType();
    var model = gson.fromJson(inputString, groupListType);
    
    0 讨论(0)
  • 2021-02-13 05:51

    I have found a solution that is actually working on Android with Kotlin for parsing JSON arrays of a given class. The solution of @Aravindraj didn't really work for me.

    val fileData = "your_json_string"
    val gson = GsonBuilder().create()
    val packagesArray = gson.fromJson(fileData , Array<YourClass>::class.java).toList()
    

    So basically, you only need to provide a class (YourClass in the example) and the JSON string. GSON will figure out the rest.

    The Gradle dependency is:

    implementation 'com.google.code.gson:gson:2.8.6'
    
    0 讨论(0)
提交回复
热议问题