Utilize Gson in Kotlin to Parse JSON with Nested Objects

I am attempting to transform the JSON below into a 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 struggling to fetch a list of options from the JSON.

I attempted the code below and successfully retrieved options, but they are nested inside dataMap. Is it feasible to retrieve a 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]))

Answer №1

By default, the variable name you choose will correspond to the respective JSON key. You can experiment with this example:

data class Person(val role: String, val ID: String, val fullname: String, val infoList: List<Details>)

If you prefer using options as your variable name, you can apply @SerializedName:

data class Person(val role: String, val ID: String, val fullname: String, @SerializedName("infoList") val options: List<Details>)

Answer №2

We need to ensure that the options provided are in the form of a String list.

The Options data class should have a parameter called dataMap which is of type List<String>.

Answer №3

Here is a suggested approach to handling JSON data:

val json = JSONObject(<your JSON string here>);
val jsonArray = json.getJSONArray();

// Utilize GSON for parsing
if (jsonArray != null) {
    val gson = Gson();
    val responseObj = gson.fromJson(jsonArray.toString(), ResponseObject[].class);
    val responseList = Arrays.asList(responseObj);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for adjusting the property of an object that has been added to an array?

I have created an object. { "heading": [{ "sections": [] }] } var obj = jQuery.parseJSON('{"header":[{"items":[]}]}'); Then I add elements to the sections var align = jQuery.parseJSON('{"align":""}'); obj["he ...

Difficulty encountered when analyzing a correctly structured JSON file in Python

I am having trouble decoding a JSON file using Python3.6 and the json module. An error that I keep encountering is: json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) Despite trying both json.load ...

What is the best method to update a nested array value within MongoDB?

Is there a way to update a nested array value within another array value? Specifically, I want to set the status as enabled where alerts.id = 2. { "_id" : ObjectId("5496a8ed49847b6cd7c7b350"), "name" : "joe", "locations" : [ { ...

How can I add a space in a JSON string when using curl on Windows?

Whenever I make this curl request (executing on a Windows cmd prompt): curl --insecure -g -X POST -H "Content-Type: application/json" -d {\"from\":\"someName\",\"message\":\"this is a message\"} https://some/website ...

The div will not receive the JSON response

I am currently working with a <script> that includes functions for autocompletion and item selection: // autocomplet : this function will be executed every time we change the text function autocomplet() { var min_length = 0; // minimum character ...

Encountering a 400 error while making a Python request that involves

Below is the code I am using to register a user through an API endpoint: import argparse import requests import ConfigParser import json import sys import logging # Configuration Parameters env = 'Pre_internal' Config = ConfigParser.ConfigPar ...

Is it possible for additional JSON properties to be deserialized into a JObject within a class during the deserialization process?

Imagine we are working with the following JSON data: { "apple": 5, "banana": "yellow", "orange": 10, "grape": "purple", } and a C# class is defined as: class Fruits { public int AppleCount { get; set;} public string BananaColor ...

Struggling to access a remote URL through jQuery's getJSON function with jsonp, but encountering difficulties

Currently, I am attempting to utilize the NPPES API. All I need to do is send it a link like this and retrieve the results using jQuery. After my research, it seems that because it is cross-domain, I should use jsonp. However, I am facing difficulties m ...

Manipulating arrays in a JSON file with JavaScript

Struggling with adding a new value to an array stored in a file.json? The array currently contains ["number1", "number2"], and you want to add "number3". However, attempts to define a variable in the JavaScript file containi ...

GSON encountered a JsonSyntaxException, with an expectation of a name at line 7, column 4

In my project, there is a Result class that has various properties and is intended to be returned as JSON. public class Result { public String objectid; public String dtype; public String type; public String name; public String descrip ...

Node js does not support iteration for DirectoryFiles

I am currently working on a program aimed at mapping all the json files within a specific directory. As I am new to JavaScript, this inquiry may not be ideal or obvious. Here is my code: const fs = require('fs'); const { glob } = require('gl ...

What is the best way to retrieve the JSON data from a POST request made through AJAX to a PHP file and save it in an array variable?

My ajax request sends JSON data to a PHP file named 'receive.php'. user_name , user_id, etc. are defined at the beginning of my script but can be changed to anything else. Below is the JavaScript code I am using: const data = { name: user_na ...

Populate ComboBox with JSON data in an ExtJS application

I am a beginner in the world of jsp and ExtJS. I have a jsp file where I am making an AJAX request to a servlet. The servlet responds with a JSON string. However, despite receiving the data, I am unable to populate a ComboBox with it. Let's take a lo ...

What is the process for parsing JSON and inserting custom text snippets?

I am working with JSON data that is generated by Spark: val df = spark.read.parquet("hdfs://xxx-namespace/20190311") val jsonStr = df.schema.json The structure of the jsonStr is as follows: { "type":"struct", "fields":[ { "na ...

Tips for parsing through extensive JSON documents containing diverse data types

In the process of developing an npm package that reads json files and validates their content against predefined json-schemas, I encountered issues when handling larger file sizes (50MB+). When attempting to parse these large files, I faced memory allocati ...

Is there a way to retrieve the initial item of a JSON array from an HTML document using Angular 2?

Within the src/assets/ directory, I have a json file called product.json with the following structure: [ { "images": "http://openclipart.org/image/300px/svg_to_png/26215/Anonymous_Leaf_Rake.png", "textBox": "empty", "comments": "empty" }, { "i ...

I require assistance with parsing the JSON outcome within a C# Windows Phone application

As a newbie in the world of developing Windows Phone apps, I am facing an issue that has been persistent even after trying out all possible solutions. The problem arises when my application tries to retrieve data from a web service, and the result it recei ...

Node: Sending JSON Values in a POST Request

I am currently working with the index.js file below: var Lob = require('lob')('test_6afa806011ecd05b39535093f7e57757695'); var residence = require('./addresses.json'); console.log(residence.residence.length); for (i = 0; i ...

Passing a Value from Child to Parent Function in Meteor: A Complete Guide

I am trying to pass the value of a result from a child element to its parent element. Initially, I used Session.set and Session.get which worked fine but I realize that using Sessions globally is not considered good practice. So, I attempted to utilize rea ...

Using JQ to structure logs in shell scripting

I've been looking to save some shell scripts into a file for collection by an agent like Fluentbit and sending them off to Cloudwatch and Datadog. I came across this example online that works effectively with the use of jq. __timestamp(){ date &quo ...