时间:2021-05-19
对List和map等结构的常用转换操作基本上可以满足我们处理的绝大多数需求,但有时项目中对json有特殊的格式规定.比如下面的json串解析:
[{"tableName":"students","tableData":[{"id":1,"name":"李坤","birthDay":"Jun 22, 2012 9:54:49 PM"},{"id":2,"name":"曹贵生","birthDay":"Jun 22, 2012 9:54:49 PM"},{"id":3,"name":"柳波","birthDay":"Jun 22, 2012 9:54:49 PM"}]},{"tableName":"teachers","tableData":[{"id":1,"name":"米老师","title":"教授"},{"id":2,"name":"丁老师","title":"讲师"}]}]
分析之后我们发现普通的方式都不好处理上面的json串.请看本文是如何处理的吧:
实体类:
import java.util.Date; public class Student { private int id; private String name; private Date birthDay; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthDay() { return birthDay; } public void setBirthDay(Date birthDay) { this.birthDay = birthDay; } @Override public String toString() { return "Student [birthDay=" + birthDay + ", id=" + id + ", name=" + name + "]"; } } public class Teacher { private int id; private String name; private String title; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Override public String toString() { return "Teacher [id=" + id + ", name=" + name + ", title=" + title + "]"; } }注意这里定义了一个TableData实体类:
import java.util.List; public class TableData { private String tableName; private List tableData; public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } public List getTableData() { return tableData; } public void setTableData(List tableData) { this.tableData = tableData; } }测试类:
(仔细看将json转回为对象的实现,这里经过两次转化,第一次转回的结果是map不是我们所期望的对象,对map再次转为json后再转为对象,我引用的是Gson2.1的jar处理正常,好像使用Gson1.6的jar会报错,所以建议用最新版本)
输出结果:
[{"tableName":"students","tableData":[{"id":1,"name":"李坤","birthDay":"Jun 22, 2012 10:04:12 PM"},{"id":2,"name":"曹贵生","birthDay":"Jun 22, 2012 10:04:12 PM"},{"id":3,"name":"柳波","birthDay":"Jun 22, 2012 10:04:12 PM"}]},{"tableName":"teachers","tableData":[{"id":1,"name":"米老师","title":"教授"},{"id":2,"name":"丁老师","title":"讲师"}]}] students Student [birthDay=Fri Jun 22 22:04:12 CST 2012, id=1, name=李坤] Student [birthDay=Fri Jun 22 22:04:12 CST 2012, id=2, name=曹贵生] Student [birthDay=Fri Jun 22 22:04:12 CST 2012, id=3, name=柳波] teachers Teacher [id=1, name=米老师, title=教授] Teacher [id=2, name=丁老师, title=讲师]注册TypeAdapter及处理Enum类型
枚举类型给我们的程序带来了好处,如何用Gson来实现与Json的互转呢?请看本文.
本文重点掌握如何自己写一个TypeAdapter及注册TypeAdapter和处理Enum类型.
实体类:
public enum PackageState { PLAY, UPDATE, UPDATING, DOWNLOAD, DOWNLOADING, } public class PackageItem { private String name; private PackageState state; private String size; public String getName() { return name; } public void setName(String name) { this.name = name; } public PackageState getState() { return state; } public void setState(PackageState state) { this.state = state; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } @Override public String toString() { return "PackageItem [name=" + name + ", size=" + size + ", state=" + state + "]"; } }自己写一个转换器实现JsonSerializer<T>接口和jsonDeserializer<T>接口:
import java.lang.reflect.Type; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; public class EnumSerializer implements JsonSerializer<PackageState>, JsonDeserializer<PackageState> { // 对象转为Json时调用,实现JsonSerializer<PackageState>接口 @Override public JsonElement serialize(PackageState state, Type arg1, JsonSerializationContext arg2) { return new JsonPrimitive(state.ordinal()); } // json转为对象时调用,实现JsonDeserializer<PackageState>接口 @Override public PackageState deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (json.getAsInt() < PackageState.values().length) return PackageState.values()[json.getAsInt()]; return null; } }测试类:
import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class GsonTest6 { public static void main(String[] args) { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(PackageState.class, new EnumSerializer()); Gson gson = gsonBuilder.create(); PackageItem item = new PackageItem(); item.setName("item_name"); item.setSize("500M"); item.setState(PackageState.UPDATING);// 这个 state是枚举值 String s = gson.toJson(item); System.out.println(s); System.out.println("--------------------------------"); PackageItem retItem = gson.fromJson(s, PackageItem.class); System.out.println(retItem); } }
输出结果(结果中已经将state的对应枚举类型转为了int类型):
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
GSON这个Java类库可以把Java对象转换成JSON,也可以把JSON字符串转换成一个相等的Java对象。Gson支持任意复杂Java对象包括没有源代码的对
Gson(GitHub:https://github.com/google/gson)是Google提供的用来在Java对象和JSON数据之间进行映射的Java
利用Gson将Map转化为JsonGson(又称GoogleGson)是Google公司发布的一个开放源代码的Java库,主要用途为串行化Java对象为JSON
Json转化为Java对象的实例详解问题:前后端数据交互时,经常会遇到Json串与Java对象转化的问题,有的Java对象中还包含了List对象等。解决方案:引
Java使用json-lib处理JSON详解【项目环境】net.sf.json-libjson-lib2.4jdk151.JSON数组对象转化为List对象;/