Example: Parsing JSON Arrays
Moshi can easily parse a JSON array into a List
of your custom objects. This example demonstrates how to do this in both Java and Kotlin.
JSON Input
Here is a simple JSON array of Card
objects.
[
{
"rank": "4",
"suit": "CLUBS"
},
{
"rank": "A",
"suit": "HEARTS"
},
{
"rank": "J",
"suit": "SPADES"
}
]
Model Classes
These are the data classes that correspond to the JSON objects.
// Card.kt
data class Card(val rank: Char, val suit: Suit)
// Suit.kt
enum class Suit { CLUBS, DIAMONDS, HEARTS, SPADES }
Parsing into a List
To tell Moshi to parse into a List<Card>
, you need to provide it with a Type
that represents this generic structure.
Kotlin Example
Kotlin's reified generics make this very clean with an extension function.
import com.squareup.moshi.Moshi
import com.squareup.moshi.adapter
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
fun main() {
val json = "..." // Your JSON array from above
val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
// Use the reified adapter extension for a clean API
val adapter = moshi.adapter<List<Card>>()
val cards: List<Card>? = adapter.fromJson(json)
println(cards)
}
Java Example
In Java, you use the Types.newParameterizedType()
helper to construct the Type
object for the list.
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import com.squareup.moshi.Types;
import java.lang.reflect.Type;
import java.util.List;
public class ParseList {
public static void main(String[] args) throws Exception {
String json = "..."; // Your JSON array from above
Moshi moshi = new Moshi.Builder().build();
Type listOfCardsType = Types.newParameterizedType(List.class, Card.class);
JsonAdapter<List<Card>> jsonAdapter = moshi.adapter(listOfCardsType);
List<Card> cards = jsonAdapter.fromJson(json);
System.out.println(cards);
}
}
Both examples will correctly parse the JSON array into a list of Card
objects.