Reputation: 611
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
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
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