例子肯定能运行成功,考虑到面向对象,所以多写了几个类。
一、日期的转换需要在Create GsonBuilder时注册日期的格式。
二、对于枚举类,如果是默认转换,则不需要做任何操作,Gson会将枚举类转换为字符串。但如果需要自定义规则来进行枚举类和字符串的转换,则需要自定义相关的类实现JsonSerializer和JsonDeserializer类。
三、含有枚举类型的Java Object:NucleonEvent
/** * */ package com.ebay.montage.pm.model; import java.util.List; import java.util.Map; /** * @author Josh Wang(Sheng) * * @email swang6@ebay.com */ public class NucleonEvent { private String id; private String host; private String odbFunction; private String source; private String format; private String classification; private long detectionTime; private long reportedTime; private Severity severity; private NucleonEventType type; private NucleonMetadata metadata; public String getId() { return id; } public void setId(String id) { this.id = id; } public NucleonEventType getType() { return type; } public void setType(NucleonEventType type) { this.type = type; } public enum NucleonEventType { nwmon_checkMem,nwmon_checkCPU_busyio; } public enum Severity { low; } public static class NucleonMetadata { private boolean passed; private String name; private List<Map<String, String>> msgs; private Map<String , Object> resultDataMap; public boolean isPassed() { return passed; } public void setPassed(boolean passed) { this.passed = passed; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Map<String, String>> getMsgs() { return msgs; } public void setMsgs(List<Map<String, String>> msgs) { this.msgs = msgs; } public Map<String, Object> getResultDataMap() { return resultDataMap; } public void setResultDataMap(Map<String, Object> resultDataMap) { this.resultDataMap = resultDataMap; } } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getOdbFunction() { return odbFunction; } public void setOdbFunction(String odbFunction) { this.odbFunction = odbFunction; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getClassification() { return classification; } public void setClassification(String classification) { this.classification = classification; } public long getDetectionTime() { return detectionTime; } public void setDetectionTime(long detectionTime) { this.detectionTime = detectionTime; } public long getReportedTime() { return reportedTime; } public void setReportedTime(long reportedTime) { this.reportedTime = reportedTime; } public Severity getSeverity() { return severity; } public void setSeverity(Severity severity) { this.severity = severity; } public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } public NucleonMetadata getMetadata() { return metadata; } public void setMetadata(NucleonMetadata metadata) { this.metadata = metadata; } @Override public String toString() { return "NucleonEvent [id=" + id + ", host=" + host + ", odbFunction=" + odbFunction + ", source=" + source + ", format=" + format + ", classification=" + classification + ", detectionTime=" + detectionTime + ", reportedTime=" + reportedTime + ", severity=" + severity + ", type=" + type + ", metadata=" + metadata.getName() + ":" + metadata.isPassed() + metadata.getMsgs() + "]"; } }
四、抽象的转换类: EventDataparser
/** * */ package com.ebay.montage.pm.handler; import com.ebay.montage.pm.model.NucleonEvent; import com.ebay.montage.pm.model.NucleonEvent.NucleonEventType; import com.ebay.montage.pm.utils.DateUtils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; /** * @author Josh Wang(Sheng) * * @email swang6@ebay.com */ public abstract class EventDataParser { public static Gson createGson() { GsonBuilder builder = new GsonBuilder(); builder.setDateFormat("yyyy-MM-dd HH:mm:ss"); builder.registerTypeAdapter(NucleonEventType.class, new NucleonEventTypeSerializer()); Gson gson = builder.create(); return gson; } /** * Parse the given JSON String to NucleonEvent * @param jsonStr * @return */ public abstract NucleonEvent fromGson(String jsonStr); /** * Parse the NucleonEvent to JSON String * @return */ public abstract String toGson(NucleonEvent event); }
如果需要使用自定义的日期转换器,需要自定义相应的Adapter 并注册相关的Adapter,如下面的Adapter将会处理所有的类型为Calendar的字段:
public static Gson createGson() { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(NucleonEventType.class, new NucleonEventTypeAdapter()); builder.registerTypeAdapter(Calendar.class, new NucleonEventCalendarAdapter()); builder.setDateFormat(DateUtils.MIDDLE_LINE_TIMESTAMP); Gson gson = builder.create(); return gson; }
package com.ebay.montage.pm.handler; import java.lang.reflect.Type; import java.util.Calendar; 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; /** * @author Josh Wang(Sheng) * * @email swang6@ebay.com */ public class NucleonEventCalendarAdapter implements JsonSerializer<Calendar>, JsonDeserializer<Calendar> { public Calendar deserialize(JsonElement json, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(json.getAsJsonPrimitive().getAsLong()); return calendar; } public JsonElement serialize(Calendar calendar, Type arg1, JsonSerializationContext arg2) { return new JsonPrimitive(Long.valueOf(calendar.getTimeInMillis())); } }
五、实际进行转换的类
/** * */ package com.ebay.montage.pm.handler; import com.ebay.montage.pm.model.NucleonEvent; /** * @author Josh Wang(Sheng) * * @email swang6@ebay.com */ public class NucleonEventDataParser extends EventDataParser { @Override public NucleonEvent fromGson(String jsonStr) { return NucleonEventDataParser.createGson().fromJson(jsonStr, NucleonEvent.class); } @Override public String toGson(NucleonEvent event) { return NucleonEventDataParser.createGson().toJson(event); } }
六、 上面的NucleonEvent中有两个枚举类:NucleonEventType 和 NucleonMetadata
我们只对NucleonEventType进行自定义的枚举类和json的转换,而对NucleonMetadata采用默认的转换。
package com.ebay.montage.pm.handler; import java.lang.reflect.Type; import com.ebay.montage.pm.model.NucleonEvent.NucleonEventType; 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; /** * * @author Josh Wang(Sheng) * * @email swang6@ebay.com */ public class NucleonEventTypeSerializer implements JsonSerializer<NucleonEventType>, JsonDeserializer<NucleonEventType> { /** * JSON to Object */ public NucleonEventType deserialize(JsonElement json, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return NucleonEventType.valueOf(json.getAsString()) ; } /** * Object to JSON */ public JsonElement serialize(NucleonEventType type, Type arg1, JsonSerializationContext arg2) { return new JsonPrimitive(type.name()); } }
七、Unit Test类
/** * */ package com.ebay.montage.pm; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import com.ebay.montage.pm.handler.NucleonEventDataParser; import com.ebay.montage.pm.model.NucleonEvent; import com.ebay.montage.pm.model.NucleonEvent.NucleonEventType; /** * @author Josh Wang(Sheng) * * @email swang6@eaby.com */ public class TestNucleonEventParser { private static String json; @BeforeClass public static void init() { json = "{\"id\": \"eventId\", \"type\":\"nwmon_checkCPU_busyio\", " + "\"format\" : \"normalizedEvent\", \"detectionTime\": \"23424234234\", " + " \"severity\":\"low\", " + "\"metadata\":{\"passed\": true,\"name\": \"Recent Changes Check\", \"msgs\": [{\"data\": \"<HTML Allowed>\"}, {\"eve\": \"<Pdf Allowed>\"}]}}"; } @Test public void fromGson() { NucleonEvent event = new NucleonEventDataParser().fromGson(json); Assert.assertEquals("eventId", event.getId()); Assert.assertEquals("nwmon_checkCPU_busyio", event.getType().toString()); System.out.println(event.toString()); } @Test public void toGson() { NucleonEvent event = new NucleonEvent(); event.setId("eventId2"); event.setType(NucleonEventType.nwmon_checkCPU_busyio); Assert.assertTrue(new NucleonEventDataParser().toGson(event).contains("eventId2")); } }