2 * Copyright (C) 2011 Google Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com
.google
.gson
.internal
.bind
;
19 import com
.google
.gson
.Gson
;
20 import com
.google
.gson
.TypeAdapter
;
21 import com
.google
.gson
.TypeAdapterFactory
;
22 import com
.google
.gson
.internal
.LinkedTreeMap
;
23 import com
.google
.gson
.reflect
.TypeToken
;
24 import com
.google
.gson
.stream
.JsonReader
;
25 import com
.google
.gson
.stream
.JsonToken
;
26 import com
.google
.gson
.stream
.JsonWriter
;
28 import java
.io
.IOException
;
29 import java
.util
.ArrayList
;
30 import java
.util
.List
;
34 * Adapts types whose static type is only 'Object'. Uses getClass() on
35 * serialization and a primitive/Map/List on deserialization.
37 public final class ObjectTypeAdapter
extends TypeAdapter
<Object
> {
38 public static final TypeAdapterFactory FACTORY
= new TypeAdapterFactory() {
39 @SuppressWarnings("unchecked")
40 public <T
> TypeAdapter
<T
> create(Gson gson
, TypeToken
<T
> type
) {
41 if (type
.getRawType() == Object
.class) {
42 return (TypeAdapter
<T
>) new ObjectTypeAdapter(gson
);
48 private final Gson gson
;
50 private ObjectTypeAdapter(Gson gson
) {
54 @Override public Object
read(JsonReader in
) throws IOException
{
55 JsonToken token
= in
.peek();
58 List
<Object
> list
= new ArrayList
<Object
>();
60 while (in
.hasNext()) {
67 Map
<String
, Object
> map
= new LinkedTreeMap
<String
, Object
>();
69 while (in
.hasNext()) {
70 map
.put(in
.nextName(), read(in
));
76 return in
.nextString();
79 return in
.nextDouble();
82 return in
.nextBoolean();
89 throw new IllegalStateException();
93 @SuppressWarnings("unchecked")
94 @Override public void write(JsonWriter out
, Object value
) throws IOException
{
100 TypeAdapter
<Object
> typeAdapter
= (TypeAdapter
<Object
>) gson
.getAdapter(value
.getClass());
101 if (typeAdapter
instanceof ObjectTypeAdapter
) {
107 typeAdapter
.write(out
, value
);