Tuesday 29 June 2021

Moshi: Convert json to list

Step 1: Get an instance of Moshi.

Moshi moshi = new Moshi.Builder().build();

 

Step 2: Get an instance of JsonAdapter to convert list to a json.

Type type = Types.newParameterizedType(List.class, String.class);
JsonAdapter<List<String>> jsonAdapter = moshi.adapter(type);

 

Step 3: Convert json to a list.

List<String> list = jsonAdapter.fromJson(json);

 

Find the below working application.

 

JsonToList.java

package com.sample.app;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import com.squareup.moshi.Types;

public class JsonToList {
    public static void main(String args[]) throws IOException {
        String json = "[\"cooking\",\"trekking\"]";

        Moshi moshi = new Moshi.Builder().build();

        Type type = Types.newParameterizedType(List.class, String.class);
        JsonAdapter<List<String>> jsonAdapter = moshi.adapter(type);

        List<String> list = jsonAdapter.fromJson(json);

        System.out.println(list);

    }
}

 

Output

[cooking, trekking]

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment