Home > Back-end >  Convert List<Integer> to JSON in Java
Convert List<Integer> to JSON in Java

Time:02-08

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!

CodePudding user response:

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) {
            //
        }

CodePudding user response:

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.

  •  Tags:  
  • Related