code_learner93
code_learner93

Reputation: 611

Convert List<Integer> to JSON in Java

How can I convert a List object in Java to a JSON object?

For example, how can I convert this:

List<Integer> myList = new ArrayList<>();
myList.add(1);
myList.add(2):
...

To this JSON:

{
    "List" : [1, 2, ...]
}

Thank you!

Upvotes: 2

Views: 4513

Answers (2)

omer blechman
omer blechman

Reputation: 386

If you want just to convert the list to json, you can use Gson:

List<Integer> myList = new ArrayList<>();
myList.add(1);
myList.add(2);
String json = new Gson().toJson(myList);

If you want that the key will be "List", you need to create a object with a member that call List and then convert it.

Upvotes: 3

Manoj Lakshan
Manoj Lakshan

Reputation: 127

If you need to convert to String use the com.fasterxml.jackson.databind.ObjectMapper

Ex:

        List<Integer> myList = new ArrayList<>();
        myList.add(1);
        myList.add(2);

        ObjectMapper mapper = new ObjectMapper();
        try {
            String json = mapper.writeValueAsString(myList);
            System.out.println("result = " + json);
            //System.out.println(json);
        } catch (JsonProcessingException e) {
            //
        }

Upvotes: 3

Related Questions