本文共 27253 字,大约阅读时间需要 90 分钟。
JSON解析类库之Gson(4) --- TypeAdapter接管序列化与反序列化
---Gson类库学习, 生成与解析json数据,json字符串与对象互转
public abstract class TypeAdapter{ /** * Writes one JSON value (an array, object, string, number, boolean or null) * for {@code value}. * * @param value the Java object to write. May be null. */ public abstract void write(JsonWriter out, T value) throws IOException; /** * Reads one JSON value (an array, object, string, number, boolean or null) * and converts it to a Java object. Returns the converted object. * * @return the converted Java object. May be null. */ public abstract T read(JsonReader in) throws IOException; // 省略了其他方法,请查看源码... }
public class User { private String id; private String name; private Date birthday; //为了代码简洁,这里移除了getter和setter方法、toString方法、构造方法等 }
package com.chunlynn.gson; import java.util.Date; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class GsonTest6 { public static void main(String[] args) { User user = new User("1", "王重阳", new Date()); Gson gson = new GsonBuilder().setPrettyPrinting()//格式化输出,这个配置有效 //User对象的序列化和序列化全都交给UserTypeAdapter了,其他配置就无效了 .registerTypeAdapter(User.class, new UserTypeAdapter()) .create(); /** * TypeAdapter流式序列化 */ String jsonString = gson.toJson(user); System.out.println("使用UserTypeAdapter:\n" + jsonString); /* * 使用UserTypeAdapter: { "id": "1", "name": "王重阳", "birth": "2017-05-02 22:39:19" } */ /** * 使用UserTypeAdapter流式反序列化 */ user = gson.fromJson(jsonString, User.class); System.out.println("流式反序列化:\n" + user); // 流式反序列化: User [id=1, name=王重阳, birthday=Tue May 02 23:47:12 CST 2017] } }
package com.chunlynn.gson; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; /** * UserTypeAdapter用来接管User对象的序列化与反序列化 * * @ClassName UserTypeAdapter * @author chunlynn * @date 2017年5月2日 * @Version V1.0 */ public class UserTypeAdapter extends TypeAdapter{ /** * 流式序列化(速度快),将序列化后的值写到流对象中 */ @Override public void write(JsonWriter out, User value) throws IOException { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); out.beginObject(); //流式序列化成对象开始 out.name("id").value(value.getId()); out.name("name").value(value.getName()); out.name("birth").value(dateFormat.format(value.getBirthday()));//格式化日期输出 //out.name("birth").value(String.valueOf(value.getBirthday()));//这样就没有格式化了 out.endObject(); //流式序列化结束 } /** * 反序列化,从json流对象中读取 */ @Override public User read(JsonReader in) throws IOException { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); User user = new User(); in.beginObject(); //流式反序列化开始 while (in.hasNext()) { //此处遍历官方推荐用if-else比较好,因为if-else可以属性值判断处理 switch (in.nextName()) { case "id": user.setId(in.nextString()); break; case "name": user.setName(in.nextString()); break; case "birthday": case "birth_day": case "birth": try { user.setBirthday(dateFormat.parse(in.nextString())); } catch (ParseException e) { e.printStackTrace(); } break; } } in.endObject(); //流式反序列化结束 return user; } }
package com.chunlynn.gson; import java.io.IOException; import java.lang.reflect.Type; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.TypeAdapter; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; public class GsonTest21 { public static void main(String[] args) { /** * TypeAdapter可以这里定义(但无法重用了),所以建议提取出来如UserListTypeAdapter.java */ TypeAdapter
> userListTypeAdapter = new TypeAdapter
>() { // 序列化[1] @Override public void write(JsonWriter out, List value) throws IOException { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); out.beginArray(); //流式序列化结束 [ for (User user : value) { //User的序列化也可以提取出来 out.beginObject(); //流式序列化结束{ out.name("id").value(user.getId()); out.name("name").value(user.getName()); out.name("birth").value(dateFormat.format(user.getBirthday())); out.endObject(); //流式序列化结束 } } out.endArray();// 流式序列化结束 [ } // 反序列化[2] @Override public List read(JsonReader in) throws IOException { List listUsers = new ArrayList (); in.beginArray(); // 开始解析流中数组中的对象 while (in.hasNext()) { try { listUsers.add(readUser(in)); // 流式对象解析 } catch (ParseException e) { e.printStackTrace(); } } in.endArray(); // 数组解析流关闭 return listUsers; } public User readUser(JsonReader in) throws IOException, ParseException { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String userId = null; String userName = null; Date userBirthdayDate = null; in.beginObject(); while (in.hasNext()) { String propertyName = in.nextName(); if (propertyName.equals("id")) { userId = in.nextString(); } else if (propertyName.equals("name")) { userName = in.nextString(); } else if (propertyName.equals("birthday") || propertyName.equals("birth")) { userBirthdayDate = dateFormat.parse(in.nextString()); } } in.endObject(); return new User(userId, userName, userBirthdayDate); } }; User user1 = new User("1", "王重阳", new Date()); User user2 = new User("2", "郭靖", new Date()); User user3 = new User("3", "黄蓉", new Date()); List userList = new ArrayList (); userList.add(user1); userList.add(user2); userList.add(user3); // 泛型的类型,序列化和反序列时都要带上该参数 Type type = new TypeToken
>() { }.getType(); Gson gson = new GsonBuilder()// //.registerTypeAdapter(type, new UserListTypeAdapter()).create();//TypeAdapter提取出来 .registerTypeAdapter(type, userListTypeAdapter).create(); String jsonString = gson.toJson(userList, type); System.out.println("泛型的序列化,使用TypeAdapter==》" + jsonString); /* 泛型的序列化,使用TypeAdapter==》 [{"id":"1","name":"王重阳","birth":"2017-05-06 21:16:04"}, {"id":"2","name":"郭靖","birth":"2017-05-06 21:16:04"}, {"id":"3","name":"黄蓉","birth":"2017-05-06 21:16:04"}] */ List retListUsers = gson.fromJson(jsonString, type); for (User u : retListUsers) { System.out.println("泛型的反序列化,使用TypeAdapter==》" + u); } //泛型的反序列化,使用TypeAdapter==》 User [id=1, name=王重阳, birthday=Sat May 06 21:16:04 CST 2017] //泛型的反序列化,使用TypeAdapter==》 User [id=2, name=郭靖, birthday=Sat May 06 21:16:04 CST 2017] //泛型的反序列化,使用TypeAdapter==》 User [id=3, name=黄蓉, birthday=Sat May 06 21:16:04 CST 2017] } }
package com.chunlynn.gson; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; /** * UserListTypeAdapter用来接管List泛型对象的序列化与反序列化 * 流式处理,高效率,任何类型都可以处理
* * @ClassName UserListTypeAdapter * @author chunlynn * @date 2017年5月6日 * @Version V1.0 */ public class UserListTypeAdapter extends TypeAdapter
> { /** * 流式序列化(速度快),将序列化后的值写到流中,需要注意开启流、关闭流 */ @Override public void write(JsonWriter out, List value) throws IOException { out.beginArray(); //1 流式数组序列化开始 "]" for (User user : value) { writeUser( out , user ); //2 流式对象序列化,"{ }" } out.endArray(); //1 流式数组序列化结束 "]" } private void writeUser(JsonWriter out, User user) throws IOException { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); out.beginObject(); //流式对象序列化开始,生成"{" out.name("id").value(user.getId()); out.name("name").value(user.getName()); out.name("birth").value(dateFormat.format(user.getBirthday())); out.endObject(); //流式对象序列化结束,生成"}" } /** * 反序列化,从JsonReader流中读取 * @throws IOException */ @Override public List read(JsonReader in) throws IOException { List listUsers = new ArrayList (); in.beginArray(); // "[" while (in.hasNext()) { try { listUsers.add(readUser(in)); // "{ }" } catch (ParseException e) { e.printStackTrace(); } } in.endArray(); //"]" return listUsers; } public User readUser(JsonReader in) throws IOException, ParseException { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String userId = null; String userName = null; Date userBirthdayDate = null; in.beginObject(); while (in.hasNext()) { String propertyName = in.nextName(); if (propertyName.equals("id")) { userId = in.nextString(); //这里也可以通过setter方法赋值 } else if (propertyName.equals("name")) { userName = in.nextString(); } else if (propertyName.equals("birthday") || propertyName.equals("birth")) { userBirthdayDate = dateFormat.parse(in.nextString()); } } in.endObject(); return new User(userId, userName, userBirthdayDate); } }
while (in.hasNext()) { String propertyName = in.nextName(); if (propertyName.equals("id")) { userId = in.nextString(); //这里也可以通过setter方法对JavaBean属性赋值 } else if (propertyName.equals("name")) { userName = in.nextString(); } else if (propertyName.equals("birthday") || propertyName.equals("birth")) { userBirthdayDate = dateFormat.parse(in.nextString()); } }
Gson gson = new GsonBuilder().setPrettyPrinting()//格式化输出 .registerTypeAdapter(Integer.class, new JsonDeserializer() { @Override public Integer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try { return json.getAsInt(); //将JSON字符串转为Integer类型 } catch (NumberFormatException e) { return -1; //空字符串转为 -1 } } }).create(); System.out.println(gson.toJson(100)); //结果:100 System.out.println(gson.fromJson("\"\"", Integer.class)); //结果-1
package com.chunlynn.gson; import java.lang.reflect.Type; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; public class GsonTest19 { public static void main(String[] args) { // 数字类型序列化器 JsonSerializernumberJsonSerializer = new JsonSerializer () { @Override public JsonElement serialize(Number src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(String.valueOf(src)); } }; /* * 可以在 GsonBuilder中注册多个TypeAdapter */ Gson gson = new GsonBuilder().registerTypeAdapter(Integer.class, numberJsonSerializer) .registerTypeAdapter(Long.class, numberJsonSerializer) .registerTypeAdapter(Float.class, numberJsonSerializer) .registerTypeAdapter(Double.class, numberJsonSerializer).create(); // 浮点型转成字符串 System.out.println(gson.toJson(100.0f));//结果:"100.0" } }
@ JsonAdapter(UserTypeAdapter.class) public class User { private String id; @Expose private String name; @SerializedName("birt") private Date birthday; //为了代码简洁,这里移除了getter和setter方法、toString方法、构造方法等 }
public class GsonTest24 { public static void main(String[] args) { User user = new User("1", "王重阳", new Date()); Gson gson = new GsonBuilder().setPrettyPrinting()//格式化输出,这个配置有效 //User对象序列化和序列化全都交给UserTypeAdapter了,其他配置就无效了 //.registerTypeAdapter(User.class, new UserTypeAdapter())// .excludeFieldsWithoutExposeAnnotation()//因 UserTypeAdapter全权接管处理,该配置无效了 .create(); /** * 流式序列化,使用@JsonAdapter来注册。 */ String jsonString = gson.toJson(user); System.out.println("使用UserTypeAdapter:\n" + jsonString); /* * 使用UserTypeAdapter: { "id": "1", "name": "王重阳", "birth": "2017-05-07 14:58:04" } */ /** * 流式反序列化,使用@JsonAdapter来注册。 */ user = gson.fromJson(jsonString, User.class); System.out.println("流式反序列化:\n" + user); /** * 流式反序列化: User [id=1, name=王重阳, birthday=Sun May 07 14:58:04 CST 2017] */ } }