Java tutorial
/* * Copyright 2015 Evgeny Dolganov (evgenij.dolganov@gmail.com). * * 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 och.util.json; import static och.util.DateUtil.*; import static och.util.Util.*; import java.lang.reflect.Array; import java.util.Collections; import java.util.List; import och.util.Util; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class GsonUtil { public static final Gson defaultGson = gsonWithFullDateFormat(); public static final Gson defaultGsonPrettyPrinting = gsonWithFullDateFormat(true); public static <T> List<T> getList(String content, Class<T> type) { return getList(content, type, new Gson()); } @SuppressWarnings("unchecked") public static <T> List<T> getList(String content, Class<T> type, Gson gson) { if (Util.isEmpty(content)) { return Collections.emptyList(); } Object arrayObject = Array.newInstance(type, 0); T[] data = (T[]) gson.fromJson(content, arrayObject.getClass()); List<T> out = list(data); return out; } public static Gson gsonWithFullDateFormat() { return gsonWithFullDateFormat(false); } public static Gson gsonWithFullDateFormat(boolean prettyPrinting) { return gsonWithDateFormat(FULL_DATE_FORMAT, prettyPrinting); } public static Gson gsonWithDateFormat(String dateFormat, boolean prettyPrinting) { GsonBuilder builder = new GsonBuilder(); builder.setDateFormat(dateFormat); if (prettyPrinting) builder.setPrettyPrinting(); return builder.create(); } }