如何在这基础上对Gson封装成一个工具类
时间: 2024-02-24 15:54:39 浏览: 33
将Gson和TypeAdapter封装成一个工具类,可以方便地在项目中使用。
以下是一个示例代码:
```
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
public class GsonUtils {
private static Gson gson;
static {
gson = new GsonBuilder()
.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeTypeAdapter())
.create();
}
public static String toJson(Object obj) {
return gson.toJson(obj);
}
public static <T> T fromJson(String json, Class<T> clazz) {
return gson.fromJson(json, clazz);
}
private static class LocalDateTimeTypeAdapter extends TypeAdapter<LocalDateTime> {
private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@Override
public void write(JsonWriter out, LocalDateTime value) throws IOException {
if (value == null) {
out.nullValue();
} else {
out.value(formatter.format(value));
}
}
@Override
public LocalDateTime read(JsonReader in) throws IOException {
if (in.peek() == null) {
return null;
} else {
String dateTimeStr = in.nextString();
return LocalDateTime.parse(dateTimeStr, formatter);
}
}
}
}
```
在使用时,只需要调用GsonUtils的toJson和fromJson方法即可。
例如:
```
// 对象转为Json字符串
Person person = new Person("张三", 18, LocalDateTime.now());
String jsonStr = GsonUtils.toJson(person);
// Json字符串转为对象
Person person2 = GsonUtils.fromJson(jsonStr, Person.class);
```
这样就可以方便地进行对象和Json字符串的互相转换,并且支持LocalDateTime的序列化和反序列化。