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 list to the json.
String json = jsonAdapter.toJson(hobbies);
Find the below working application.
ListToJson.java
package com.sample.app;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import com.squareup.moshi.Types;
public class ListToJson {
public static void main(String args[]) {
List<String> hobbies = Arrays.asList("cooking", "trekking");
Moshi moshi = new Moshi.Builder().build();
Type type = Types.newParameterizedType(List.class, String.class);
JsonAdapter<List<String>> jsonAdapter = moshi.adapter(type);
String json = jsonAdapter.toJson(hobbies);
System.out.println(json);
}
}
Output
["cooking","trekking"]
Previous Next Home
No comments:
Post a Comment