All about Json and Moshi Library
JavaScript Object Notation - JSON
A lightweight format for storing and transporting data. It is often used when data is sent from a server to a web page.
JSON Syntax :
- Data is always in (name: value) pair
- Data is separated by commas
- Curly braces hold objects
- Square brackets hold arrays
JSON is built on two structures:
- A collection of name/value pairs. In various languages, this is realised as an object, record, struct, dictionary, hash table, keyed list, or associative array.
- An ordered list of values. In most languages, this is realised as an
array, vector, list, or sequence.
It then goes on to describe the two structures as:
Note that the starting and ending characters are curly brackets and square brackets respectively.
Json nodes will start with a square bracket [ ] or with curly bracket { }
[ ] = represents the beginning of a JSONArray node so we need to use getJSONArray()
{ } = represents the beginning of a JSONObject node so we need to use getJSONobject()
Moshi Library
It is a modern JSON library for Android, Java and Kotlin.
It makes it easy to parse JSON into Java and Kotlin classes.
It understands Kotlin's non-nullable types and default parameter values.
implementation("com.squareup.moshi:moshi-kotlin:1.13.0")
val moshi = Moshi.Builder()
.addLast(KotlinJsonAdapterFactory())
.add( "Add Your Custom Adapters")
.build()
When you use Kotlin with Moshi you may use reflection, codegen or both
Reflection Adapter uses Kotlin's reflection library to convert your Kotlin classes to and from JSON.
We enable it by adding the KotlinJsonAdapterFactory to Moshi.Builder.
Codegen
Moshi's Kotlin codegen support can be used as an annotation processor via Kapt or KSP(Kotlin SymbolProcessor)
It generates a small and fast adapter for each of your Kotlin classes at compile-time.
Enable it by annotating each class that you want to encode as JSON:
@JsonClass(generateAdapter = true)
data class BlackjackHand(
val hidden_card: Card,
val visible_cards: List<Card>
)
for KSP we have to add the library
plugins {
id("com.google.devtools.ksp").version("1.6.10-1.0.4") // Or latest version of KSP
}
dependencies {
ksp("com.squareup.moshi:moshi-kotlin-codegen:1.13.0")
}
Comments
Post a Comment