NET2Java之七:JSON序列化
Json序列化和反序列化也是开发常用功能之一,.NET中有Json.NET,System.Text.Json,Java中比较常用的则有Jackson、Gson、FastJson,为了更好的演示,我们先定义一个User类:
public class User {
private String name;
private int age;
private LocalDateTime time;
public User(String name, int age, LocalDateTime time) {
this.name = name;
this.age = age;
this.time = time;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public LocalDateTime getTime() {
return time;
}
public void setTime(LocalDateTime time) {
this.time = time;
}
}
JackJson
最受欢迎的Json序列化框架。
Maven依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.0</version>
</dependency>
正常来说引入这个就可以使用了,但是如果使用LocalDataTime类型则会抛出异常,所以需要额外引入:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.13.5</version>
</dependency>
使用示例
package com.lmmplat.net2java.common;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.lmmplat.net2java.bean.User;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* Jackson使用示例。
*/
public class JacksonUtil {
/**
* Java对象转Json。
*
* @throws JsonProcessingException
*/
public static void Obj2Json() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
User user = new User("朴不起", 28, LocalDateTime.now());
JavaTimeModule timeModule=new JavaTimeModule();
timeModule.addSerializer(LocalDateTime.class,new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
mapper.registerModule(timeModule);
String json = mapper.writeValueAsString(user);
System.out.println(json);
}
/**
* Json转Java对象。
*
* @throws JsonProcessingException
*/
public static void Json2Obj() throws JsonProcessingException {
String json = "{\"name\":\"朴正欢\",\"age\":30,\"time\":\"2024-04-29 14:31:59\"}";
ObjectMapper mapper = new ObjectMapper();
JavaTimeModule timeModule=new JavaTimeModule();
timeModule.addDeserializer(LocalDateTime.class,new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
mapper.registerModule(timeModule);
User user = mapper.readValue(json, User.class);
System.out.println(user.getName() + ":" + user.getAge());
}
}
Jackson是默认是序列化null值的,如果不需要,可以在实体上添加:
@JsonInclude(JsonInclude.Include.NON_NULL)
private String name;
则字段为null时,会被直接忽略,这样可以减少传输,也可以通过mapper..setSerializationInclusion(Include.NON_NULL)来整体配置,反序列化时,如果没有无参构造,反序列化时抛出异常,则需要以通过注解的方式来解决:
@JsonCreator
public User(@JsonProperty("name") String name,@JsonProperty("age") int age,@JsonProperty("time") LocalDateTime time){
this.name=name;
this.age=age;
this.time=time;
}
此外还有一些比较常用的注解,如JsonIgnore、JsonInclude、JsonAlias等。
Gson
谷歌出品,目前功能最全的Json解析神器。
Maven依赖
<!-- Gson依赖 -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
使用示例:
package com.lmmplat.net2java.common;
import com.google.gson.*;
import com.lmmplat.net2java.bean.User;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* Gson使用示例。
*/
public class GsonUtil {
/**
* Java对象转Json。
*/
public static void Obj2Json() {
User user = new User("朴不起", 28, LocalDateTime.now());
Gson gson = new GsonBuilder()
//LocalDateTime的兼容
.registerTypeAdapter(LocalDateTime.class, (JsonSerializer<LocalDateTime>) (time, gtype, context) -> new JsonPrimitive(time.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))))
.create();
String json = gson.toJson(user);
System.out.println(json);
}
/**
* Json转Java对象。
*/
public static void Json2Obj() {
String json = "{\"name\":\"朴正欢\",\"age\":30,\"time\":\"2024-04-29 14:31:59\"}";
Gson gson = new GsonBuilder()
.registerTypeAdapter(LocalDateTime.class, (JsonDeserializer<LocalDateTime>) (jsonStr, gtype, context) -> {
String datetime = jsonStr.getAsJsonPrimitive().getAsString();
return LocalDateTime.parse(datetime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
})
.create();
User user = gson.fromJson(json, User.class);
System.out.println(user.getName() + ":" + user.getAge());
}
}
FastJson
FastJson是阿里出品的高性能Json API,简单转换速度几块,但在复杂类型的处理上存在不少问题,为了解决这些问题,阿里又迭代了版本2,所以这里我们直接上手2:
Maven依赖
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.24</version>
</dependency>
使用示例
package com.lmmplat.net2java.common;
import com.alibaba.fastjson2.JSON;
import com.lmmplat.net2java.bean.User;
import java.time.LocalDateTime;
/**
* FastJson使用示例。
*/
public class FastJsonUtil {
/**
* Java对象转Json。
*/
public static void Obj2Json() {
User user = new User("朴不起", 28, LocalDateTime.now());
String json = JSON.toJSONString(user);
System.out.println(json);
}
/**
* Json转Java对象。
*/
public static void Json2Obj() {
String json = "{\"name\":\"朴正欢\",\"age\":30,\"time\":\"2024-04-29 14:31:59\"}";
User user = JSON.parseObject(json, User.class);
System.out.println(user.getName() + ":" + user.getAge());
}
}

浙公网安备 33010602011771号