1 /* 2 * Copyright 2004-2010 the Seasar Foundation and the Others. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 13 * either express or implied. See the License for the specific language 14 * governing permissions and limitations under the License. 15 */ 16 17 package org.seasar.cubby.plugins.gson.spi; 18 19 import org.seasar.cubby.spi.ContainerProvider; 20 import org.seasar.cubby.spi.JsonProvider; 21 import org.seasar.cubby.spi.ProviderFactory; 22 import org.seasar.cubby.spi.container.Container; 23 import org.seasar.cubby.spi.container.LookupException; 24 25 import com.google.gson.Gson; 26 27 /** 28 * <a href="http://code.google.com/p/google-gson/">Google Gson</a> を用いる 29 * {@link JsonProvider} の実装です。 30 * <p> 31 * {@link Container} から {@link Gson} のインスタンスを取得できる場合はそのインスタンスによって処理します。そうでない場合は 32 * {@link Gson#Gson()} によって生成したインスタンスによって処理します。 33 * </p> 34 * 35 * @see <a href="http://code.google.com/p/google-gson/">Google Gson</a> 36 * @see <a 37 * href="http://sites.google.com/site/gson/gson-user-guide">Gson User Guide</a> 38 * @author baba 39 */ 40 public class GsonJsonProvider implements JsonProvider { 41 42 /** GSON */ 43 private Gson gson; 44 45 /** 46 * {@inheritDoc} 47 */ 48 public String toJson(final Object o) { 49 if (this.gson == null) { 50 this.gson = createGson(); 51 } 52 return this.gson.toJson(o); 53 } 54 55 /** 56 * {@link Gson} のインスタンスを構築します。 57 * <p> 58 * {@link Container} から {@link Gson} のインスタンス取得できる場合はそのインスタンスを、そうでない場合は 59 * {@link Gson#Gson()} によって生成したインスタンスを返します。 60 * </p> 61 * 62 * @return {@link Gson} のインスタンス 63 */ 64 private Gson createGson() { 65 final Container container = ProviderFactory 66 .get(ContainerProvider.class).getContainer(); 67 try { 68 return container.lookup(Gson.class); 69 } catch (final LookupException e) { 70 return new Gson(); 71 } 72 } 73 74 }