Java中处理JSON数据,主要涉及到将Java对象转换为JSON字符串(序列化)以及将JSON字符串转换为Java对象(反序列化),以下是如何在Java中编写和处理JSON数据的详细指南。
选择合适的JSON库
Java本身并不提供内置的JSON处理功能,因此我们需要借助第三方库,最常用的JSON库包括:
库名 | 特点 | 适用场景 |
---|---|---|
Gson | Google开发,API简单易用,支持注解和自定义序列化/反序列化。 | 快速上手,适合中小型项目。 |
Jackson | 功能强大,性能优秀,支持流式解析和树模型,与Spring生态集成良好。 | 大型项目或对性能要求较高的场景。 |
Fastjson | 阿里巴巴开源,速度快,支持本地化特性(如日期格式)。 | 对性能要求高且需要本地化支持的场景。 |
JSON.simple | 轻量级,API简单,适合简单JSON处理。 | 仅需基础功能且依赖较少的场景。 |
使用Gson处理JSON
添加Gson依赖
如果使用Maven,可以在pom.xml
中添加以下依赖:
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.10.1</version> </dependency>
创建Java对象
假设我们有一个Person
类:
public class Person { private String name; private int age; private String email; // 构造方法、Getter和Setter public Person(String name, int age, String email) { this.name = name; this.age = age; this.email = email; } // Getter和Setter方法 }
将Java对象转换为JSON字符串
import com.google.gson.Gson; public class Main { public static void main(String[] args) { Person person = new Person("张三", 30, "zhangsan@example.com"); Gson gson = new Gson(); String jsonString = gson.toJson(person); System.out.println(jsonString); // 输出: {"name":"张三","age":30,"email":"zhangsan@example.com"} } }
格式化输出
为了让JSON字符串更易读,可以使用GsonBuilder
进行格式化:
import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class Main { public static void main(String[] args) { Person person = new Person("张三", 30, "zhangsan@example.com"); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String jsonString = gson.toJson(person); System.out.println(jsonString); // 输出: // { // "name": "张三", // "age": 30, // "email": "zhangsan@example.com" // } } }
处理Null值
默认情况下,Gson会忽略值为null
的字段,如果希望保留null
值,可以配置serializeNulls()
:
Gson gson = new GsonBuilder().serializeNulls().create();
自定义序列化策略
自定义日期格式:
import com.google.gson.; import java.text.SimpleDateFormat; import java.util.Date; public class DateSerializer implements JsonSerializer<Date> { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Override public JsonElement serialize(Date date, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(dateFormat.format(date)); } } // 使用示例 Gson gson = new GsonBuilder() .registerTypeAdapter(Date.class, new DateSerializer()) .create();
处理嵌套对象和集合
import java.util.List; class Address { private String street; private String city; // 构造方法、Getter和Setter } class Person { private String name; private int age; private Address address; private List<String> hobbies; // 构造方法、Getter和Setter } // 使用示例 Address address = new Address("123 Main St", "Anytown"); List<String> hobbies = List.of("Reading", "Hiking"); Person person = new Person("Charlie", 40, address, hobbies); String json = gson.toJson(person); System.out.println(json); // 输出: {"name":"Charlie","age":40,"address":{"street":"123 Main St","city":"Anytown"},"hobbies":["Reading","Hiking"]}
使用Jackson处理JSON
添加Jackson依赖
如果使用Maven,可以在pom.xml
中添加以下依赖:
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.15.2</version> </dependency>
将Java对象转换为JSON字符串
import com.fasterxml.jackson.databind.ObjectMapper; public class Main { public static void main(String[] args) throws Exception { Person person = new Person("张三", 30, "zhangsan@example.com"); ObjectMapper mapper = new ObjectMapper(); String jsonString = mapper.writeValueAsString(person); System.out.println(jsonString); // 输出: {"name":"张三","age":30,"email":"zhangsan@example.com"} } }
格式化输出
mapper.writerWithDefaultPrettyPrinter().writeValueAsString(person);
处理Null值
Jackson默认会忽略null
值,但可以通过配置改变:
mapper.getFactory().getConfig().with(DeserializationFeature.FAIL_ON_NULL_CREATORS).with(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
自定义序列化策略
自定义日期格式:
import com.fasterxml.jackson.annotation.JsonFormat; import java.util.Date; public class Person { @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss") private Date birthday; // 其他字段和方法 }
处理嵌套对象和集合
Jackson会自动处理嵌套对象和集合,无需额外操作。
使用Fastjson处理JSON
添加Fastjson依赖
如果使用Maven,可以在pom.xml
中添加以下依赖:
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.83</version> </dependency>
将Java对象转换为JSON字符串
import com.alibaba.fastjson.JSON; public class Main { public static void main(String[] args) { Person person = new Person("张三", 30, "zhangsan@example.com"); String jsonString = JSON.toJSONString(person); System.out.println(jsonString); // 输出: {"name":"张三","age":30,"email":"zhangsan@example.com"} } }
格式化输出
String jsonString = JSON.toJSONString(person, true); // 第二个参数为true表示格式化输出
处理Null值
Fastjson默认会保留null
值,如果不需要可以配置:
JSON.toJSONString(person, SerializerFeature.WriteMapNullValue);
自定义序列化策略
自定义日期格式:
import com.alibaba.fastjson.serializer.SerializeConfig; import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer; import java.util.Date; import java.text.SimpleDateFormat; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.
原创文章,发布者:酷盾叔,转转请注明出处:https://www.kd.cn/ask/55972.html