Example how to start new Empty activity, add library to Gradle, and create JSON with
GSON.
First start "Empty Activity":
In next step in my case I have choosen language Kotlin, Minimum SDK API 21:
In Android -> Gradle Scripts -> build.gradle:
I have added:
implementation 'com.google.code.gson:gson:2.9.0'
Now my dependecies look like:
dependencies {
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
implementation 'com.google.code.gson:gson:2.9.0'
}
Go to File -> Sync Project with Gradle Files:
In MainActivity write something like:
internal class Albums {
var title: String? = null
var message: String? = null
var errors = arrayOf<String>()
var total: String? = null
var total_pages = 0
var page = 0
var limit: String? = null
}
and
val albums = Albums()
albums.title = "Free Music Archive - Albums"
albums.message = ""
albums.total = "11259"
albums.total_pages = 2252
albums.page = 1
albums.limit = "5"
val builder = GsonBuilder()
val gson: Gson = builder.create()
System.out.println(gson.toJson(albums))
My MainActivity now looks like:
package com.example.myapplication
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.google.gson.Gson
import com.google.gson.GsonBuilder
internal class Albums {
var title: String? = null
var message: String? = null
var errors = arrayOf<String>()
var total: String? = null
var total_pages = 0
var page = 0
var limit: String? = null
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val albums = Albums()
albums.title = "Free Music Archive - Albums"
albums.message = ""
albums.total = "11259"
albums.total_pages = 2252
albums.page = 1
albums.limit = "5"
val builder = GsonBuilder()
val gson: Gson = builder.create()
System.out.println(gson.toJson(albums))
}
}