Convert list to JSON Java

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

Your browser isn’t supported anymore. Update it to get the best YouTube experience and our latest features. Learn more

Remind me later

  • Given a list of user defined objects, we would like to convert list of pojo objects to JSON (and JSON to list of objects).
  • We will use the jackson’s objectmapper, to serialize list of objects to JSON & deserialize JSON to List of objects.
  • We will create Person class & we will perform following operations with Person class.
    • Convert List of Person objects to JSON
    • Convert the JSON to List of Person objects.
  • We have already discussed (similar transformations):
    • Convert Objects to/from JSON (jackson)
    • Convert map to/from JSON      (jackson)
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.7.1</version> </dependency>
  • Person class containing attributes is as follows:
package org.learn; public class Person { public String firstName; public String lastName; public int age; public Person() { } public Person(String firstName, String lastName, int age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } public String toString() { return "[" + firstName + " " + lastName + " " + age +"]"; } }

JSONListConverter  class is responsible for performing following operations.

  1. Convert List of Person objects to JSON String in java.
  2. Convert JSON String to List of Person objects in java.
package org.learn; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; public class JSONListConverter { public static void main( String[] args ) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); //Set pretty printing of json objectMapper.enable(SerializationFeature.INDENT_OUTPUT); //Define map which will be converted to JSON List<Person> personList = Stream.of( new Person("Mike", "harvey", 34), new Person("Nick", "young", 75), new Person("Jack", "slater", 21 ), new Person("gary", "hudson", 55)) .collect(Collectors.toList()); //1. Convert List of Person objects to JSON String arrayToJson = objectMapper.writeValueAsString(personList); System.out.println("1. Convert List of person objects to JSON :"); System.out.println(arrayToJson); //2. Convert JSON to List of Person objects //Define Custom Type reference for List<Person> type TypeReference<List<Person>> mapType = new TypeReference<List<Person>>() {}; List<Person> jsonToPersonList = objectMapper.readValue(arrayToJson, mapType); System.out.println("\n2. Convert JSON to List of person objects :"); //Print list of person objects output using Java 8 jsonToPersonList.forEach(System.out::println); } }

Download Example Code – Jackson List Object to JSON

3. Output – list of objects to/from JSON in java (jackson objectmapper)

1. Convert List of person objects to JSON : [ { "firstName" : "Mike", "lastName" : "harvey", "age" : 34 }, { "firstName" : "Nick", "lastName" : "young", "age" : 75 }, { "firstName" : "Jack", "lastName" : "slater", "age" : 21 }, { "firstName" : "gary", "lastName" : "hudson", "age" : 55 } ] 2. Convert JSON to List of person objects : [Mike harvey 34] [Nick young 75] [Jack slater 21] [gary hudson 55]

JSONObject is a very popular in terms of transferring data between two systems. Now a days everything is transferred between the systems is JSONObject.

It’s been long time I’ve been playing with JSONObject, JSONArray and more. In this tutorial we will go over steps on how to convert Java ArrayList to JSONObject.

We will use Google GSON utility for the same. Just include below dependencies to your Java Enterprise project and you should be good.

Google GSON Maven Dependency

    <groupId>com.google.code.gson</groupId>

    <artifactId>gson</artifactId>

As per today, version 2.8.4 is the latest version. Please update to latest version if you could.

In our Java Program, we will create ArrayList first and then will convert it to JSONObject.

Let’s get started:

  • Create Java Class CrunchifyArrayListToJsonObject.java
  • Create ArrayList named crunchify
  • Add 6 companyNames to ArrayList
  • Print ArrayList
  • Convert it to JSONObject/JSONArray using Google JSON
  • Print JSONObject

Here is a complete code:

CrunchifyArrayListToJsonObject.java

package crunchify.com.tutorial;

import java.util.ArrayList;

import com.google.gson.Gson;

import com.google.gson.GsonBuilder;

* Program: Best way to convert Java ArrayList to JSONObject

public class CrunchifyArrayListToJsonObject {

public static void main(String a[]) {

ArrayList<String> crunchify = new ArrayList<String>();

crunchify.add("Facebook");

crunchify.add("Crunchify");

crunchify.add("Twitter");

crunchify.add("Snapchat");

crunchify.add("Microsoft");

log("Raw ArrayList ===> " + crunchify);

// Use this builder to construct a Gson instance when you need to set configuration options other than the default.

GsonBuilder gsonBuilder = new GsonBuilder();

// This is the main class for using Gson. Gson is typically used by first constructing a Gson instance and then invoking toJson(Object) or fromJson(String, Class) methods on it.

// Gson instances are Thread-safe so you can reuse them freely across multiple threads.

Gson gson = gsonBuilder.create();

String JSONObject = gson.toJson(crunchify);

log("\nConverted JSONObject ==> " + JSONObject);

Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();

String prettyJson = prettyGson.toJson(crunchify);

log("\nPretty JSONObject ==> " + prettyJson);

private static void log(Object print) {

System.out.println(print);

Eclipse console output:

Raw ArrayList ===> [Google, Facebook, Crunchify, Twitter, Snapchat, Microsoft]

Converted JSONObject ==> ["Google","Facebook","Crunchify","Twitter","Snapchat","Microsoft"]

I hope you can use this simple utility to convert any Java Objects to JSONObject or JSONArray.

If you liked this article, then please share it on social media. Still have any questions about an article, leave us a comment.

Video liên quan

Chủ đề