Google Gson 변환 Json 문자열 및 개체(날짜, 열거된 변환)

예는 틀림없이 성공적으로 실행될 것이다. 대상을 고려하여 몇 가지 종류를 더 썼다.
 
1. 날짜의 변환은 Create GsonBuilder에 등록된 날짜의 형식이 필요합니다.
 
2. 열거 클래스에 대해 기본 변환이라면 아무런 조작도 하지 않아도 된다. Gson은 열거 클래스를 문자열로 변환한다.그러나 매개 클래스와 문자열의 변환을 위한 사용자 정의 규칙이 필요하다면, 사용자 정의 관련 클래스가 Json Serializer와 Json Deserializer 클래스를 실현해야 한다.
 
3. 열거 유형을 포함하는 Java Object:Nucleon Event
 
/**
 * 
 */
package com.ebay.montage.pm.model;

import java.util.List;
import java.util.Map;

/**
 * @author Josh Wang(Sheng)
 *
 * @email  [email protected]
 */
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() + "]";
	}

	

	
}

 
 
4. 추상적인 변환 클래스: 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  [email protected]
 */
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);
}

 
사용자 정의 날짜 변환기를 사용하려면 해당 어댑터를 사용자 정의하고 관련 어댑터를 등록해야 합니다. 예를 들어 다음 어댑터는 모든 유형의 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  [email protected]
 */
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()));
	}

	

}

 
5. 실제적으로 전환하는 유형
 
/**
 * 
 */
package com.ebay.montage.pm.handler;

import com.ebay.montage.pm.model.NucleonEvent;

/**
 * @author Josh Wang(Sheng)
 *
 * @email  [email protected]
 */
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);
	}

}

 
6. 위의 Nucleon Event에는 두 개의 매거 클래스가 있는데 그것이 바로 Nucleon Event Type과 Nucleon Metadata이다.
우리는 Nucleon EventType에 대해 사용자 정의 매거진 클래스와 json만 변환하고, Nucleon Metadatadata에 대해서는 기본 변환을 사용합니다.
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  [email protected]
 */
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());
	}


}

 
 
7. 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  [email protected]
 */
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"));
	}
}

 
 
 

좋은 웹페이지 즐겨찾기