Java json 格式化

这篇博客展示了如何使用Gson, Jackson和org.json库将JSON字符串转换为Java对象,并输出格式化的JSON。通过示例代码,我们可以看到这三种库在处理JSON数据时的不同方法和输出效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考地址

依赖

	implementation("com.google.code.gson:gson:2.9.0")
	implementation("org.json:json:20220320")

	implementation("com.fasterxml.jackson.core:jackson-core:2.11.2")
	implementation("com.fasterxml.jackson.core:jackson-databind:2.11.2")

代码

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParser;
import org.json.JSONArray;
import org.json.JSONObject;

public class Main {

	public static void main(String[] args) throws Exception{

		// Gson
		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		System.out.println(gson.toJson(JsonParser.parseString("[{\"name\": \"tom1\"}, {   \"name\": \"tom2\"}]")));
		System.out.println(gson.toJson(JsonParser.parseString("\n"
				+ "{\n"
				+ "  \"name\": \"tom\",\"age\": 12\n"
				+ "}")));

		// JSONArray
		System.out.println(new JSONArray("[{\"name\": \"tom1\"}, {   \"name\": \"tom2\"}]").toString(4));
		System.out.println( new JSONObject("\n"
				+ "{\n"
				+ "  \"name\": \"tom\",\"age\": 12\n"
				+ "}").toString(4));

		// jackson
		ObjectMapper mapper = new ObjectMapper();

		System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(mapper.readTree("[{\"name\": \"tom1\"}, {   \"name\": \"tom2\"}]")));

		System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(mapper.readTree("\n"
				+ "{\n"
				+ "  \"name\": \"tom\",\"age\": 12\n"
				+ "}")));

	}
}

结果

[
  {
    "name": "tom1"
  },
  {
    "name": "tom2"
  }
]
{
  "name": "tom",
  "age": 12
}
[
    {"name": "tom1"},
    {"name": "tom2"}
]
{
    "name": "tom",
    "age": 12
}
[ {
  "name" : "tom1"
}, {
  "name" : "tom2"
} ]
{
  "name" : "tom",
  "age" : 12
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值