Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin convert json array to model list using GSON

Tags:

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":["aaa","bbb"],
  "name":"My Expense"
 },
 {
  "description":"My expense to others","
  items":["aaa","bbb"],
  "name":"My Expense"
 }]

and the GroupModel class is:

class GroupModel {
    var name: String? = null
    var description: String? = null
    var items: MutableList<String>? = null

    constructor(name: String, description: String, items: MutableList<String>) {
        this.name = name
        this.description = description
        this.items = items
    }
}

and trying the following code results in an Exception:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

The code:

var model = gson.fromJson<Array<GroupModel>>(inputString, GroupModel::class.java)
like image 711
Ayyanar Avatar asked Feb 18 '18 16:02

Ayyanar


People also ask

Does Gson work with Kotlin?

Google Gson is one of the most popular libraries for handling JSON objects, and many popular programming languages support it, including Kotlin. In this tutorial, we'll explore how to serialize and deserialize JSON arrays with Kotlin using Gson.

Can we convert JSON array to list in Java?

We can convert a JSON array to a list using the ObjectMapper class. It has a useful method readValue() which takes a JSON string and converts it to the object class specified in the second argument.


2 Answers

[{
  "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'
like image 142
BIS Tech Avatar answered Sep 21 '22 13:09

BIS Tech


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'
like image 30
xarlymg89 Avatar answered Sep 17 '22 13:09

xarlymg89