Vinit ...
Vinit ...

Reputation: 1459

Parse nested JSON using Gson Kotlin

I am trying to convert the following json into list data object:

[
  {
    "type": "PHOTO",
    "id": "pic1",
    "title": "Photo 1",
    "dataMap": {}
  },
  {
    "type": "SINGLE_CHOICE",
    "id": "choice1",
    "title": "Photo 1 choice",
    "dataMap": {
      "options": [
        "Good",
        "OK",
        "Bad"
      ]
    }
  },
    ---
    ---
]

code:

data class User(val type: String, val id: String, val title: String, val options: List<Options>)

data class Options(val dataMap: String)

fun getUserListFromAssert(context: Context, fileName: String) : List<User>{
    val gson = Gson()
    val listPersonType = object : TypeToken<List<User>>() {}.type

    var users: List<User> = gson.fromJson(getJsonDataFromAsset(context, fileName), listPersonType)

    return users;
}

Now call getUserListFromAssert:

var users: List<User>  = TemporaryData.getUserListFromAssert(this, "users.json")

    users.forEach { s -> Log.d(TAG, "onCreate: $s") }

Output:

User(type=PHOTO, id=pic1, title=Photo 1, options=null)
---

I am not able to get List of options from json.

I tried the following code and am able to retrieve options but inside dataMap. Is this possible to retrieve list of options directly in the user class?

data class User(val type: String, val id: String, val title: String, @SerializedName("dataMap") val options: dataMap)
data class dataMap(val options: List<String>)

Output:

User(type=PHOTO, id=pic1, title=Photo 1, options=dataMap(options=null))
User(type=SINGLE_CHOICE, id=choice1, title=Photo 1 choice, options=dataMap(options=[Good, OK, Bad]))

Upvotes: 1

Views: 1965

Answers (3)

Naufal Prakoso
Naufal Prakoso

Reputation: 90

By default, your variable name will refer to your JSON key. So you can try this:

data class User(val type: String, val id: String, val title: String, val dataMap: List<Options>)

But, if you still want options for your variable name. You can use @SerializedName:

data class User(val type: String, val id: String, val title: String, @SerializedName("dataMap") val options: List<Options>)

Upvotes: 2

Diksha Pruthi
Diksha Pruthi

Reputation: 354

You can try this

val jsonObject = JSONObject(<your JSON string result>);
val jsonArray = jsonObject.getJSONArray();

//use GSON to parse
if (jsonArray != null) {
   val gson = Gson();
   val objResponse = gson.fromJson(jsonArray.toString(), ObjResponse[]::class.java);
   val objResponseList = Arrays.asList(objResponse);
}

Upvotes: 0

Viktor Petrovski
Viktor Petrovski

Reputation: 796

Options should be a List of Strings.

data class Options(val dataMap: List<String>)

Upvotes: 0

Related Questions