Java 数组转换为 JSON 数组的方法有:使用 Jackson 库:通过 ObjectMapper 将数组转换为 JSON 字符串。使用 GSON 库:通过 Gson 实例将数组转换为 JSON 字符串。

Java 数组转换为 JSON 数组
方法:
1. 使用 Jackson 库:
<code class="java">import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ConvertArrayToJsonArray {
public static void main(String[] args) throws JsonProcessingException {
// 创建一个字符串数组
String[] array = {"apple", "banana", "cherry"};
// 使用 Jackson 库将数组转换为 JSON 数组
ObjectMapper mapper = new ObjectMapper();
String jsonArray = mapper.writeValueAsString(array);
// 打印 JSON 数组
System.out.println(jsonArray);
}
}</code>2. 使用 GSON 库:
立即学习“Java免费学习笔记(深入)”;
<code class="java">import com.google.gson.Gson;
public class ConvertArrayToJsonArray {
public static void main(String[] args) {
// 创建一个字符串数组
String[] array = {"apple", "banana", "cherry"};
// 使用 GSON 库将数组转换为 JSON 数组
Gson gson = new Gson();
String jsonArray = gson.toJson(array);
// 打印 JSON 数组
System.out.println(jsonArray);
}
}</code>输出:
<code class="json">["apple", "banana", "cherry"]</code>
以上就是JAVA设置json数组怎么写的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号