How do I convert a list to JSON in Java?

How do I convert a list to JSON in Java?

Add Comment
  • 1 Answer(s)

    To convert a list to JSON in Java, you can use the following steps:

    1. Import the JSON library.
    2. Create a JSONArray object.
    3. Add the elements of the list to the JSONArray object.
    4. Convert the JSONArray object to a JSON string.

    Here is an example of how to convert a list to JSON in Java:

    Java
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import org.json.JSONArray;
    
    public class Main {
        public static void main(String[] args) {
            List<String> list = new ArrayList<>(Arrays.asList("one", "two", "three"));
    
            JSONArray jsonArray = new JSONArray(list);
    
            String jsonString = jsonArray.toString();
    
            System.out.println(jsonString);
        }
    }
    

    Output:

    JSON
    ["one", "two", "three"]
    

    You can also use the ObjectMapper class from the Jackson library to convert a list to JSON in Java. The ObjectMapper class provides a more powerful and flexible way to convert Java objects to JSON and vice versa.

    Here is an example of how to convert a list to JSON in Java using the ObjectMapper class:

    Java
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    public class Main {
        public static void main(String[] args) throws Exception {
            List<String> list = new ArrayList<>(Arrays.asList("one", "two", "three"));
    
            ObjectMapper objectMapper = new ObjectMapper();
    
            String jsonString = objectMapper.writeValueAsString(list);
    
            System.out.println(jsonString);
        }
    }
    

    Output:

    JSON
    ["one", "two", "three"]
    

    Which method you choose to convert a list to JSON in Java depends on your specific needs and preferences. If you need a simple and straightforward solution, you can use the JSONArray class. If you need a more powerful and flexible solution, you can use the ObjectMapper class from the Jackson library.

    Answered on October 15, 2023.
    Add Comment
  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.