Parsing Json into Kotlin Data Class with GSON

I am working with a Java POJO class that looks like this:

class Topic {
    @SerializedName("id")
    long id;
    @SerializedName("name")
    String name;
}

In addition, I also have a Kotlin data class structured as follows:

 data class Topic(val id: Long, val name: String)

I am wondering how to assign JSON keys to variables in the Kotlin data class similar to using the @SerializedName annotation in Java variables?

Answer โ„–1

Data Class Example:

data class Subject(
  @SerializedName("id") val id: Int, 
  @SerializedName("name") val name: String, 
  @SerializedName("category") val category: String,
  @SerializedName("description") val description: String
)

Convert to JSON:

val gson = Gson()
val jsonSubject = gson.toJson(subject)

Parse from JSON:

val jsonString = getJsonString()
val subject = gson.fromJson(jsonString, Subject::class.java)

Answer โ„–2

Answer from Anton Golovin

Specifics

  • Gson version: 2.8.5
  • Android Studio 3.1.4
  • Kotlin version: 1.2.60

The Fix

To solve the issue, create a data class and implement the JSONConvertable interface.

interface JSONConvertable {
     fun toJSON(): String = Gson().toJson(this)
}

inline fun <reified T: JSONConvertable> String.toObject(): T = Gson().fromJson(this, T::class.java)

How to Use

Data Class Example:

data class User(
    @SerializedName("id") val id: Int,
    @SerializedName("email") val email: String,
    @SerializedName("authentication_token") val authenticationToken: String) : JSONConvertable

Converting from JSON:

val json = "..."
val object = json.toObject<User>()

Converting to JSON:

val json = object.toJSON()

Answer โ„–3

If you're working with Kotlin classes, you can follow a similar approach.

class InventoryMoveRequest {
    @SerializedName("userEntryStartDate")
    @Expose
    var userEntryStartDate: String? = null
    @SerializedName("userEntryEndDate")
    @Expose
    var userEntryEndDate: String? = null
    @SerializedName("location")
    @Expose
    var location: Location? = null
    @SerializedName("containers")
    @Expose
    var containers: Containers? = null
}

For nested classes, you can handle them in a similar way by providing the Serialize name for the Class.

@Entity(tableName = "location")
class Location {

    @SerializedName("rows")
    var rows: List<Row>? = null
    @SerializedName("totalRows")
    var totalRows: Long? = null

}

When receiving a response from the server, each key will map to JSON format.

To convert a List to JSON:

val gson = Gson()
val json = gson.toJson(topic)

And to convert from JSON back to an Object:

val json = getJson()
val topic = gson.fromJson(json, Topic::class.java)

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

Techniques for transmitting stringified JSON data from the view to the controller in MVC4

I am struggling to properly send a stringified JSON object when a button is clicked. Despite being able to call the necessary Action method upon button click, the parameter is passed as null. MemberLogin.cshtml <input type="button" value="ยป Continue" ...

Errors occurred when trying to use Jquery to handle a JSON response

enter code here function customPaging(action, action1, page) { alert("in customPaging"); $.getJSON("./paging.do?action="+escape(action)+"&p="+escape(action1)+"&str="+escape(page), function(data){ alert("Length: "+data.length); var options = ...

Retrieve data from a MySQL database and input it into a PHP URL

I am having trouble retrieving a username from the database to fetch the corresponding JSON data for that user. The current code I have implemented is generating a 500 error, possibly due to some issue with $json variable... Could someone offer assistance ...

The JSON parsing encountered an error with the response having "status":200 and "statusText":"OK"

I am encountering a parse error when trying to send a JSON object. {"readyState":4,"responseText":"","status":200,"statusText":"OK"} Here is the code snippet: var data = { fb_id: response.id, email: response.email, name: response.name, first_nam ...

Converting strings into the right values through parsing

I have a JSON response that contains multiple suggestions, but I only want to parse and extract the 4 "collation" results: jQuery191029421305245357143_1380819227858( { "responseHeader": { "status": 0, "QTime": 127 }, "command": ...

Is it possible to run test steps for a bilingual (English and Arabic) web application using cucumber and selenium web driver?

I am interested in automating a series of test steps for interface testing in both English and Arabic. The steps include logging in, selecting products, and adding them to the cart. To achieve this, I have created a feature file in Cucumber and written al ...

Extracting JSON data from a column in Presto

In my Presto table, there is a specific structure that I am trying to achieve. Specific Date Specific Rates 1/1/2022 {"USD":"725.275","GBP":"29.275000000000002","CAD":"0.713352"} 1/2/202 ...

What are the methods for accessing data from a local Json file on an html page without using a server?

Looking to access a local Json file from an HTML page, but encountering challenges in reading the file on Chrome and IE. Is there a method to achieve this without relying on a web server? ...

What is the method to retrieve the label linked to a checkbox in Selenium automation tool?

Is there a way to display the label associated with a checkbox, such as 'checkbox 1' or 'checkbox 2', in the example provided below? Checkbox Items: <input type="checkbox" value="cb1" name="checkboxes[]">Checkbox 1 & ...

What is the method for editing individual rows in a data table in Spring MVC when the edit button is clicked?

Every time I click on <a id="myBtn"><i class="fa fa-pencil" style="color:OliveDrab;"></i></a>, I only get a modal on the first row click, and it appears empty. I've searched through many internet resources, but none of them pro ...

What steps should I take to retrieve JSON data using fetch from my Express server?

After several attempts to use fetch for retrieving JSON data from my express server, I have encountered some issues. While the fetch function works well with JSONPlaceholder, it seems to fail when accessing my express code. Below is the snippet of my fetc ...

Unable to access the SignOut button by clicking

Looking for some assistance! I'm having trouble clicking on the 'Sign Out' button, here is a screenshot from Firebug: <li class="dropdown open"> <a class="dropdown-toggle" aria-expanded="true" aria-haspopup="true" role="button" dat ...

How can I retrieve a specific key from a nested array while using ng-repeat to iterate through it

I have successfully created a code snippet that retrieves JSON data and displays it in HTML using AngularJS. <div class="activity" ng-app="stream" ng-controller="streamCtrl"> <ul ng-repeat="x in myData"> <p class="au ...

Exclude JSON Property if it Lacks a Certain Value

I'm attempting to retrieve specific values from a DynamoDB database where the name is "john". The challenge I'm facing is that although I can fetch values containing name: john from a mapped list, I also receive additional unwanted values. When ...

The data retrieved by the $.getJSON method is not displaying as a line graph

I am currently dealing with two files searh_journal.php <script type="text/javascript"> function submitForm() { var form = document.myform; var dataString = $(form).serialize(); $.ajax({ type: 'POST', url: & ...

Creating an automated sequence of $http requests to sequentially retrieve JSON files with numbered filenames in Angular 1.2

I have a series of JSON files (page1.json, page2.json, etc.) that store the layout details for our website pages. Initially, I would load each page's data as needed and everything was functioning smoothly. However, it is now necessary for all page da ...

sending a JSON object from the controller to a JSP page

I need to transfer all the data from my database in the form of a JSON array to a JSP page so that it can be retrieved using AJAX. EmployeeController public class EmployeeController { @Autowired private EmployeeService employeeService; @RequestMapping( ...

Having trouble navigating to the element within the frame on Selenium using Java

I have been using Selenium for testing web pages, and currently I am working on a webpage that contains frames. The structure is as follows: <frameset title="Application Content"> <frame name="main" src="qweMain.jsp?langua ...

Incorporate another parameter into the current JSON data

I am currently facing the following scenario: Several servlets are setting the HttpServletResponse content-type to application/json. This is how I am outputting my JSON: out.write(new Gson().toJson(myObject)); where myObject is an object that structur ...

Strange JSON format detected when consuming the Python Hug REST API in a .NET environment

When using a Hug REST endpoint to consume JSON in .net, there are issues with embedded characters that I am facing. See the example below for a complete failure. Any assistance would be greatly appreciated. Python @hug.post('/test') def test(re ...