[{
  "description":"My expense to others",
  "items":["aaa","bbb"],
  "name":"My Expense"
 },
 {
  "description":"My expense to others","
  items":["aaa","bbb"],
  "name":"My Expense"
 }]

Kotlin Code

val gson = GsonBuilder().create()
val Model= gson.fromJson(body,Array<GroupModel>::class.java).toList()

Gradle

implementation 'com.google.code.gson:gson:2.8.5'
Answer from BIS Tech on Stack Overflow
๐ŸŒ
GitHub
gist.github.com โ€บ luiszacheu โ€บ cd1aa1f431c421294bd937d233f06fb7
Gson FromJson List (Kotlin) ยท GitHub
Save luiszacheu/cd1aa1f431c421294bd937d233f06fb7 to your computer and use it in GitHub Desktop. Download ZIP ยท Gson FromJson List (Kotlin) Raw ยท ListFromJson.kt ยท This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below.
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ kotlin โ€บ kotlin collections โ€บ parsing json arrays in kotlin with gson
Parsing JSON Arrays in Kotlin with Gson | Baeldung on Kotlin
March 19, 2024 - Gson has the built-in feature of parsing to and from an array or a list automatically into JSON objects and vice versa. For instance, we can define a list of Author objects with just the name and serialize it to a JSON Array object:
๐ŸŒ
Kotlin
kotlinlang.org โ€บ api โ€บ kotlinx.serialization โ€บ kotlinx-serialization-json โ€บ kotlinx.serialization.json โ€บ -json-array
JsonArray | kotlinx.serialization โ€“ Kotlin Programming Language
kotlinx-serialization-json/kotlinx.serialization.json/JsonArray ยท @Serializable(with = JsonArraySerializer::class ยท )class JsonArray(content: List<JsonElement>) : JsonElement, List<JsonElement> (source) Class representing JSON array, consisting of indexed values, where value is arbitrary JsonElement ยท
Find elsewhere
Top answer
1 of 9
276

You can parse the JSONArray directly, don't need to wrap your Post class with PostEntity one more time and don't need new JSONObject().toString() either:

Gson gson = new Gson();
String jsonOutput = "Your JSON String";
Type listType = new TypeToken<List<Post>>(){}.getType();
List<Post> posts = gson.fromJson(jsonOutput, listType);
2 of 9
8

I was looking for a way to parse object arrays in a more generic way; here is my contribution:

CollectionDeserializer.java:

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

public class CollectionDeserializer implements JsonDeserializer<Collection<?>> {

    @Override
    public Collection<?> deserialize(JsonElement json, Type typeOfT,
            JsonDeserializationContext context) throws JsonParseException {
        Type realType = ((ParameterizedType)typeOfT).getActualTypeArguments()[0];

        return parseAsArrayList(json, realType);
    }

    /**
     * @param serializedData
     * @param type
     * @return
     */
    @SuppressWarnings("unchecked")
    public <T> ArrayList<T> parseAsArrayList(JsonElement json, T type) {
        ArrayList<T> newArray = new ArrayList<T>();
        Gson gson = new Gson();

        JsonArray array= json.getAsJsonArray();
        Iterator<JsonElement> iterator = array.iterator();

        while(iterator.hasNext()){
            JsonElement json2 = (JsonElement)iterator.next();
            T object = (T) gson.fromJson(json2, (Class<?>)type);
            newArray.add(object);
        }

        return newArray;
    }

}

JSONParsingTest.java:

public class JSONParsingTest {

    List<World> worlds;

    @Test
    public void grantThatDeserializerWorksAndParseObjectArrays(){

        String worldAsString = "{\"worlds\": [" +
            "{\"name\":\"name1\",\"id\":1}," +
            "{\"name\":\"name2\",\"id\":2}," +
            "{\"name\":\"name3\",\"id\":3}" +
        "]}";

        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(Collection.class, new CollectionDeserializer());
        Gson gson = builder.create();
        Object decoded = gson.fromJson((String)worldAsString, JSONParsingTest.class);

        assertNotNull(decoded);
        assertTrue(JSONParsingTest.class.isInstance(decoded));

        JSONParsingTest decodedObject = (JSONParsingTest)decoded;
        assertEquals(3, decodedObject.worlds.size());
        assertEquals((Long)2L, decodedObject.worlds.get(1).getId());
    }
}

World.java:

public class World {
    private String name;
    private Long id;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

}
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ converting kotlin data class from json using gson
Converting Kotlin Data Class from JSON using GSON - Scaler Topics
November 6, 2023 - This process allows you to easily convert a JSON array into a list or array of Kotlin data class objects, enabling you to work with collections of objects in your application. To parse JSON into a Kotlin Map using the GSON library, you can follow these steps:
๐ŸŒ
Rip Tutorial
riptutorial.com โ€บ parsing json array to generic class using gson
Android Tutorial => Parsing json array to generic class using Gson
We can parse this array into a Custom Tweets (tweets list container) object manually, but it is easier to do it with fromJson method: Gson gson = new Gson(); String jsonArray = "...."; Tweets tweets = gson.fromJson(jsonArray, Tweets.class); ...
๐ŸŒ
Futurestud.io
futurestud.io โ€บ tutorials โ€บ gson-mapping-of-arrays-and-lists-of-objects
Gson โ€” Mapping of Arrays and Lists of Objects - Future Studio
June 2, 2016 - Welcome back to another blog post in our Gson series. After reviewing the basics of Gson, model annotations and mapping of nested objects, we'll go on to a core feature: mapping of Arrays and Lists. Almost every data model out there utilizes some form of list.
๐ŸŒ
BezKoder
bezkoder.com โ€บ home โ€บ kotlin โ€“ convert object to/from json string using gson
Kotlin - Convert object to/from JSON string using Gson - BezKoder
April 11, 2020 - <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> </dependency> ... Go to Maven Repository and download .jar file. We will need a plain Class first. Letโ€™s call it Tutorial. ... package com.bezkoder.kotlin.jsonparser.models class Tutorial( val title: String, val author: String, val categories: List<String> ) { override fun toString(): String { return "Category [title: ${this.title}, author: ${this.author}, categories: ${this.categories}]" } }
๐ŸŒ
GitHub
github.com โ€บ SalomonBrys โ€บ Kotson
GitHub - SalomonBrys/Kotson: Kotlin bindings for JSON manipulation via Gson
When providing a non-specialized generic type, typeToken<List<*>> will return Class<List> (while Gson's mechanism will return a ParameterizedType). If you really need a ParameterizedType for a non-specialized generic type, you can use the gsonTypeToken function. Kotson allows you to simply convert a jsonElement to a primitive, a JsonObject or a JsonArray:
Starred by 708 users
Forked by 35 users
Languages ย  Kotlin 100.0% | Kotlin 100.0%
Top answer
1 of 7
322

Create this inline fun:

inline fun <reified T> Gson.fromJson(json: String) = fromJson<T>(json, object: TypeToken<T>() {}.type)

and then you can call it in this way:

val turns = Gson().fromJson<Turns>(pref.turns)
// or
val turns: Turns = Gson().fromJson(pref.turns)

Previous Alternatives:

ALTERNATIVE 1:

val turnsType = object : TypeToken<List<Turns>>() {}.type
val turns = Gson().fromJson<List<Turns>>(pref.turns, turnsType)

You have to put object : and the specific type in fromJson<List<Turns>>


ALTERNATIVE 2:

As @cypressious mention it can be achieved also in this way:

inline fun <reified T> genericType() = object: TypeToken<T>() {}.type

use as:

val turnsType = genericType<List<Turns>>()
2 of 7
37

This solves the problem:

val turnsType = object : TypeToken<List<Turns>>() {}.type
val turns = Gson().fromJson<List<Turns>>(pref.turns, turnsType)

The first line creates an object expression that descends from TypeToken and then gets the Java Type from that. Then the Gson().fromJson method either needs the type specified for the result of the function (which should match the TypeToken created). Two versions of this work, as above or:

val turns: List<Turns> = Gson().fromJson(pref.turns, turnsType)

To make it easier to create the TypeToken you can create a helper function, which is required to be inline so that it can use reified type parameters:

inline fun <reified T> genericType() = object: TypeToken<T>() {}.type

Which can then be used in either of these ways:

val turnsType = genericType<List<Turns>>()
// or
val turnsType: List<Turns> = genericType()

And the whole process can be wrapped into an extension function for the Gson instance:

inline fun <reified T> Gson.fromJson(json: String) = this.fromJson<T>(json, object: TypeToken<T>() {}.type)

So that you can just call Gson and not worry about the TypeToken at all:

val turns = Gson().fromJson<Turns>(pref.turns)
// or
val turns: Turns = Gson().fromJson(pref.turns)

Here Kotlin is using type inference from one side of the assignment or the other, and reified generics for an inline function to pass through the full type (without erasure), and using that to construct a TypeToken and also make the call to Gson

๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 61739674 โ€บ kotlin-reading-in-list-of-objects-from-json-using-gson-and-type-generics-andr
Kotlin - Reading in list of objects from JSON using GSON and Type Generics (Android) - Stack Overflow
May 12, 2020 - The following snippet works to read in a list of Villager POJOs from the JSON file in Android assets. // this works fun getVillagersFromJSON(context: Context): List<Villager> { val jsonFileString = getJsonDataFromAsset(context, "villagers.json") return Gson().fromJson(jsonFileString, object : TypeToken<List<Villager>>() {}.type) }