可以使用JSON库来将Java数组转换为JSON字符串。以下是一个使用Jackson库的示例代码:
import com.fasterxml.jackson.databind.ObjectMapper; public class ArrayToJsonExample { public static void main(String[] args) { int[] array = {1, 2, 3, 4, 5}; // 创建ObjectMapper对象 ObjectMapper objectMapper = new ObjectMapper(); try { // 将Java数组转换为JSON字符串 String json = objectMapper.writeValueAsString(array); System.out.println(json); } catch (Exception e) { e.printStackTrace(); } } }
输出结果将是一个包含数组元素的JSON字符串:[1,2,3,4,5]
。