Classes in this File | Line Coverage | Branch Coverage | Complexity | ||||
GsonJsonProvider |
|
| 2.5;2.5 |
1 | /* | |
2 | * Copyright 2004-2009 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 | package org.seasar.cubby.plugins.gson.spi; | |
17 | ||
18 | import org.seasar.cubby.spi.ContainerProvider; | |
19 | import org.seasar.cubby.spi.JsonProvider; | |
20 | import org.seasar.cubby.spi.ProviderFactory; | |
21 | import org.seasar.cubby.spi.container.Container; | |
22 | import org.seasar.cubby.spi.container.LookupException; | |
23 | ||
24 | import com.google.gson.Gson; | |
25 | ||
26 | /** | |
27 | * <a href="http://code.google.com/p/google-gson/">Google Gson</a> を用いる | |
28 | * {@link JsonProvider} の実装です。 | |
29 | * <p> | |
30 | * {@link Container} から {@link Gson} のインスタンスを取得できる場合はそのインスタンスによって処理します。そうでない場合は | |
31 | * {@link Gson#Gson()} によって生成したインスタンスによって処理します。 | |
32 | * </p> | |
33 | * | |
34 | * @see <a href="http://code.google.com/p/google-gson/">Google Gson</a> | |
35 | * @see <a | |
36 | * href="http://sites.google.com/site/gson/gson-user-guide">Gson User Guide</a> | |
37 | * @author baba | |
38 | */ | |
39 | 2 | public class GsonJsonProvider implements JsonProvider { |
40 | ||
41 | /** GSON */ | |
42 | private Gson gson; | |
43 | ||
44 | /** | |
45 | * {@inheritDoc} | |
46 | */ | |
47 | public String toJson(final Object o) { | |
48 | 2 | if (this.gson == null) { |
49 | 2 | this.gson = createGson(); |
50 | } | |
51 | 2 | return this.gson.toJson(o); |
52 | } | |
53 | ||
54 | /** | |
55 | * {@link Gson} のインスタンスを構築します。 | |
56 | * <p> | |
57 | * {@link Container} から {@link Gson} のインスタンス取得できる場合はそのインスタンスを、そうでない場合は | |
58 | * {@link Gson#Gson()} によって生成したインスタンスを返します。 | |
59 | * </p> | |
60 | * | |
61 | * @return {@link Gson} のインスタンス | |
62 | */ | |
63 | private Gson createGson() { | |
64 | 2 | final Container container = ProviderFactory |
65 | .get(ContainerProvider.class).getContainer(); | |
66 | try { | |
67 | 2 | return container.lookup(Gson.class); |
68 | 1 | } catch (final LookupException e) { |
69 | 1 | return new Gson(); |
70 | } | |
71 | } | |
72 | ||
73 | } |