Convert Java List to Json String using Jackson


Post Banner
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class JavaListToJsonString {

    public static void main(String[] args) {
        try {

            List<String> insuranceCompaniesList = new ArrayList<>();
            insuranceCompaniesList.add("Chubb Ltd.");
            insuranceCompaniesList.add("Travelers Companies Inc.");
            insuranceCompaniesList.add("Liberty Mutual");
            insuranceCompaniesList.add("Zurich Insurance Group");
            insuranceCompaniesList.add("Berkshire Hathaway Inc.");
            insuranceCompaniesList.add("American International Group (AIG)");

            ObjectMapper objectMapper = new ObjectMapper();
            String jsonString = objectMapper.writeValueAsString(insuranceCompaniesList);
            System.out.println(jsonString);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Output:
[
  "Chubb Ltd.",
  "Travelers Companies Inc.",
  "Liberty Mutual",
  "Zurich Insurance Group",
  "Berkshire Hathaway Inc.",
  "American International Group (AIG)"
]
-


Have Questions? Post them here!

Top Hashtags:

Advertisements

Advertisements




Advertisements