All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.butor.json.JsonHelper Maven / Gradle / Ivy

Go to download

This module enables fast and easy creation of sync., async., req./resp., req./resp. stream HTTP/json services.

The newest version!
/**
 * Copyright 2013-2019 Butor Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.butor.json;

import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Iterables;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.JsonSyntaxException;

public class JsonHelper {
	private Logger logger = LoggerFactory.getLogger(getClass());

	private JsonParser jsonParser = new JsonParser();

	private static class GmtDateTypeAdapter implements JsonSerializer, JsonDeserializer {
		private final DateFormat dateFormat;
		
		private GmtDateTypeAdapter() {
			dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
			dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
		}

		@Override
		public synchronized JsonElement serialize(Date date, Type type,
				JsonSerializationContext jsonSerializationContext) {
			synchronized (dateFormat) {
				String dateFormatAsString = dateFormat.format(date);
				return new JsonPrimitive(dateFormatAsString);
			}
		}

		@Override
		public synchronized Date deserialize(JsonElement jsonElement, Type type,
				JsonDeserializationContext jsonDeserializationContext) {
			try {
				synchronized (dateFormat) {
					return dateFormat.parse(jsonElement.getAsString());
				}
			} catch (ParseException e) {
				throw new JsonSyntaxException(jsonElement.getAsString(), e);
			}
		}
	}

	private Gson mapper;
	/**
	 * Allow to use specifi date format,such: yyyy-MM-dd HH:mm:ss.SSS
	 */
	public JsonHelper(String dateFormat) {
		GsonBuilder gb = new GsonBuilder();
		gb.setDateFormat(dateFormat);
		mapper = gb.create();
	}
	/**
	 * By default will use GMT date format with milliseconds
	 */
	public JsonHelper() {
		GsonBuilder gb = new GsonBuilder();
		gb.registerTypeAdapter(Date.class, new GmtDateTypeAdapter());
		mapper = gb.create();
	}
	public String serialize(Object obj) {
		try {
			if (obj == null) {
				return null;
			}
			return mapper.toJson(obj);
		} catch (Exception e) {
			logger.warn(String.format("Failed to serialize obj : %s", obj), e);
		}
		return null;
	}
	/**
	 *@deprecated Replaced by
	 *    {@link #deserialize(String, Type)}
	 *
	 */
	@Deprecated
	public  T deserialize(String obj, Class cls) {
		if (obj == null)
			return null;
		try {
			return mapper.fromJson(obj, cls);
		} catch (Exception e) {
			logger.warn(String.format("Failed to deserialize obj: %s", obj), e);
		}
		return null;
	}

	public  T deserialize(String obj, Type type) {
		if (obj == null)
			return null;
		try {
			return mapper.fromJson(obj, type);
		} catch (Exception e) {
			logger.warn(String.format("Failed to deserialize obj: %s", obj), e);
		}
		return null;
	}
	
	public Object[] deserializeServiceArgs(String json) {
		// Inspired by http://stackoverflow.com/a/14369566/5024208
		Object[] arr = Iterables.toArray(jsonParser.parse(json).getAsJsonArray(), Object.class);
		
		// reserve/add first arg for context that will be set later
		Object[] result = new Object[arr.length +1];
		
		for (int i=0; i[] types) {
		if (args == null) {
			logger.warn("Got null object array!");
			return null;
		}
		
		if (types == null) {
			logger.warn("Got null types!");
			return null;
		}

		if (args.length != types.length) {
			logger.warn("args length={} must be equals to types types length={}!", args.length, types.length);
			return null;
		}
		Object[] result = new Object[args.length];
		
		// skip first arg that is reserved for context arg
		for (int i=1; i[] types) {
		Object[] arr = deserializeServiceArgs(json);
		return parseServiceArgs(arr, types);
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy