溫馨提示×

java數(shù)組怎么轉(zhuǎn)json字符串

小億
272
2023-08-31 21:56:49
欄目: 編程語言

可以使用JSON庫來將Java數(shù)組轉(zhuǎn)換為JSON字符串。以下是一個使用Jackson庫的示例代碼:

import com.fasterxml.jackson.databind.ObjectMapper;
public class ArrayToJsonExample {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
// 創(chuàng)建ObjectMapper對象
ObjectMapper objectMapper = new ObjectMapper();
try {
// 將Java數(shù)組轉(zhuǎn)換為JSON字符串
String json = objectMapper.writeValueAsString(array);
System.out.println(json);
} catch (Exception e) {
e.printStackTrace();
}
}
}

輸出結(jié)果將是一個包含數(shù)組元素的JSON字符串:[1,2,3,4,5]。

0