001/**
002 * Copyright 2014 Tampere University of Technology, Pori Department
003 * 
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 * 
008 *   http://www.apache.org/licenses/LICENSE-2.0
009 * 
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package core.tut.pori.utils;
017
018import java.lang.reflect.Type;
019import java.util.Date;
020
021import com.google.gson.Gson;
022import com.google.gson.GsonBuilder;
023import com.google.gson.JsonDeserializationContext;
024import com.google.gson.JsonDeserializer;
025import com.google.gson.JsonElement;
026import com.google.gson.JsonParseException;
027import com.google.gson.JsonPrimitive;
028import com.google.gson.JsonSerializationContext;
029import com.google.gson.JsonSerializer;
030
031/**
032 * JSON formatter.
033 * 
034 * This class can be used to marshal objects to JSON output, and unmarshal objects from JSON input.
035 * 
036 * Uses the default GSON parser with extended support for ISODATE (ISO 8601) using java date objects.
037 */
038public final class JSONFormatter {
039  /**
040   * 
041   */
042  private JSONFormatter(){
043    // nothing needed
044  }
045  
046  
047  /**
048   * Initialize Gson serializer with ISO Date parsers
049   * @return new serializer instance
050   */
051  public static Gson createGsonSerializer(){
052    GsonBuilder builder = new GsonBuilder();
053    builder.registerTypeAdapter(Date.class, new JsonSerializer<Date>() {
054
055      @Override
056      public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
057        if(src == null){
058          return null;
059        }else{
060          return new JsonPrimitive(StringUtils.dateToISOString(src));
061        }
062      }
063    });
064    
065    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
066
067      @Override
068      public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
069        return (json == null ? null : StringUtils.ISOStringToDate(json.getAsString()));
070      }
071    });
072    
073    return builder.create();
074  }
075}