├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── GsonDesignDocument.md ├── LICENSE ├── README.md ├── ReleaseProcess.md ├── UserGuide.md ├── codegen ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── google │ │ │ └── gson │ │ │ └── codegen │ │ │ ├── CodeGen.java │ │ │ ├── GeneratedTypeAdapter.java │ │ │ ├── GeneratedTypeAdapterProcessor.java │ │ │ └── JavaWriter.java │ └── resources │ │ └── META-INF │ │ └── services │ │ └── javax.annotation.processing.Processor │ └── test │ └── java │ └── com │ └── google │ └── gson │ └── codegen │ └── functional │ ├── CodeGenFunctionalTest.java │ └── Order.java ├── examples └── android-proguard-example │ ├── AndroidManifest.xml │ ├── default.properties │ ├── proguard.cfg │ ├── res │ ├── drawable │ │ └── icon.png │ ├── layout │ │ └── main.xml │ └── values │ │ └── strings.xml │ └── src │ └── com │ └── google │ └── gson │ └── examples │ └── android │ ├── GsonProguardExampleActivity.java │ └── model │ ├── Cart.java │ └── LineItem.java ├── extras ├── pom.xml └── src │ ├── main │ └── java │ │ └── com │ │ └── google │ │ └── gson │ │ ├── extras │ │ └── examples │ │ │ └── rawcollections │ │ │ └── RawCollectionsExample.java │ │ ├── graph │ │ └── GraphAdapterBuilder.java │ │ ├── interceptors │ │ ├── Intercept.java │ │ ├── InterceptorFactory.java │ │ └── JsonPostDeserializer.java │ │ └── typeadapters │ │ ├── PostConstructAdapterFactory.java │ │ ├── RuntimeTypeAdapterFactory.java │ │ └── UtcDateTypeAdapter.java │ └── test │ └── java │ └── com │ └── google │ └── gson │ ├── graph │ └── GraphAdapterBuilderTest.java │ ├── interceptors │ └── InterceptorTest.java │ └── typeadapters │ ├── PostConstructAdapterFactoryTest.java │ ├── RuntimeTypeAdapterFactoryTest.java │ └── UtcDateTypeAdapterTest.java ├── gson ├── Gson 2.1 notes.txt ├── IKGson.jar ├── LICENSE ├── README ├── assembly-descriptor.xml ├── bnd.bnd ├── docs │ └── javadocs │ │ ├── allclasses-frame.html │ │ ├── allclasses-noframe.html │ │ ├── com │ │ └── google │ │ │ └── gson │ │ │ ├── ExclusionStrategy.html │ │ │ ├── FieldAttributes.html │ │ │ ├── FieldNamingPolicy.html │ │ │ ├── FieldNamingStrategy.html │ │ │ ├── Gson.html │ │ │ ├── GsonBuilder.html │ │ │ ├── InstanceCreator.html │ │ │ ├── JsonArray.html │ │ │ ├── JsonDeserializationContext.html │ │ │ ├── JsonDeserializer.html │ │ │ ├── JsonElement.html │ │ │ ├── JsonIOException.html │ │ │ ├── JsonNull.html │ │ │ ├── JsonObject.html │ │ │ ├── JsonParseException.html │ │ │ ├── JsonParser.html │ │ │ ├── JsonPrimitive.html │ │ │ ├── JsonSerializationContext.html │ │ │ ├── JsonSerializer.html │ │ │ ├── JsonStreamParser.html │ │ │ ├── JsonSyntaxException.html │ │ │ ├── LongSerializationPolicy.html │ │ │ ├── TypeAdapter.html │ │ │ ├── TypeAdapterFactory.html │ │ │ ├── annotations │ │ │ ├── Expose.html │ │ │ ├── JsonAdapter.html │ │ │ ├── SerializedName.html │ │ │ ├── Since.html │ │ │ ├── Until.html │ │ │ ├── class-use │ │ │ │ ├── Expose.html │ │ │ │ ├── JsonAdapter.html │ │ │ │ ├── SerializedName.html │ │ │ │ ├── Since.html │ │ │ │ └── Until.html │ │ │ ├── package-frame.html │ │ │ ├── package-summary.html │ │ │ ├── package-tree.html │ │ │ └── package-use.html │ │ │ ├── class-use │ │ │ ├── ExclusionStrategy.html │ │ │ ├── FieldAttributes.html │ │ │ ├── FieldNamingPolicy.html │ │ │ ├── FieldNamingStrategy.html │ │ │ ├── Gson.html │ │ │ ├── GsonBuilder.html │ │ │ ├── InstanceCreator.html │ │ │ ├── JsonArray.html │ │ │ ├── JsonDeserializationContext.html │ │ │ ├── JsonDeserializer.html │ │ │ ├── JsonElement.html │ │ │ ├── JsonIOException.html │ │ │ ├── JsonNull.html │ │ │ ├── JsonObject.html │ │ │ ├── JsonParseException.html │ │ │ ├── JsonParser.html │ │ │ ├── JsonPrimitive.html │ │ │ ├── JsonSerializationContext.html │ │ │ ├── JsonSerializer.html │ │ │ ├── JsonStreamParser.html │ │ │ ├── JsonSyntaxException.html │ │ │ ├── LongSerializationPolicy.html │ │ │ ├── TypeAdapter.html │ │ │ └── TypeAdapterFactory.html │ │ │ ├── package-frame.html │ │ │ ├── package-summary.html │ │ │ ├── package-tree.html │ │ │ ├── package-use.html │ │ │ ├── reflect │ │ │ ├── TypeToken.html │ │ │ ├── class-use │ │ │ │ └── TypeToken.html │ │ │ ├── package-frame.html │ │ │ ├── package-summary.html │ │ │ ├── package-tree.html │ │ │ └── package-use.html │ │ │ └── stream │ │ │ ├── JsonReader.html │ │ │ ├── JsonToken.html │ │ │ ├── JsonWriter.html │ │ │ ├── MalformedJsonException.html │ │ │ ├── class-use │ │ │ ├── JsonReader.html │ │ │ ├── JsonToken.html │ │ │ ├── JsonWriter.html │ │ │ └── MalformedJsonException.html │ │ │ ├── package-frame.html │ │ │ ├── package-summary.html │ │ │ ├── package-tree.html │ │ │ └── package-use.html │ │ ├── constant-values.html │ │ ├── deprecated-list.html │ │ ├── help-doc.html │ │ ├── index-all.html │ │ ├── index.html │ │ ├── overview-frame.html │ │ ├── overview-summary.html │ │ ├── overview-tree.html │ │ ├── package-list │ │ ├── resources │ │ └── inherit.gif │ │ ├── script.js │ │ ├── serialized-form.html │ │ └── stylesheet.css ├── pom.xml └── src │ ├── main │ └── java │ │ └── com │ │ └── google │ │ └── gson │ │ ├── DefaultDateTypeAdapter.java │ │ ├── ExclusionStrategy.java │ │ ├── FieldAttributes.java │ │ ├── FieldNamingPolicy.java │ │ ├── FieldNamingStrategy.java │ │ ├── Gson.java │ │ ├── GsonBuilder.java │ │ ├── InstanceCreator.java │ │ ├── JsonArray.java │ │ ├── JsonDeserializationContext.java │ │ ├── JsonDeserializer.java │ │ ├── JsonElement.java │ │ ├── JsonIOException.java │ │ ├── JsonNull.java │ │ ├── JsonObject.java │ │ ├── JsonParseException.java │ │ ├── JsonParser.java │ │ ├── JsonPrimitive.java │ │ ├── JsonSerializationContext.java │ │ ├── JsonSerializer.java │ │ ├── JsonStreamParser.java │ │ ├── JsonSyntaxException.java │ │ ├── LongSerializationPolicy.java │ │ ├── TypeAdapter.java │ │ ├── TypeAdapterFactory.java │ │ ├── annotations │ │ ├── Expose.java │ │ ├── JsonAdapter.java │ │ ├── SerializedName.java │ │ ├── Since.java │ │ ├── Until.java │ │ └── package-info.java │ │ ├── internal │ │ ├── $Gson$Preconditions.java │ │ ├── $Gson$Types.java │ │ ├── ConstructorConstructor.java │ │ ├── Excluder.java │ │ ├── JsonReaderInternalAccess.java │ │ ├── LazilyParsedNumber.java │ │ ├── LinkedHashTreeMap.java │ │ ├── LinkedTreeMap.java │ │ ├── ObjectConstructor.java │ │ ├── Primitives.java │ │ ├── Streams.java │ │ ├── UnsafeAllocator.java │ │ ├── bind │ │ │ ├── ArrayTypeAdapter.java │ │ │ ├── CollectionTypeAdapterFactory.java │ │ │ ├── DateTypeAdapter.java │ │ │ ├── JsonAdapterAnnotationTypeAdapterFactory.java │ │ │ ├── JsonTreeReader.java │ │ │ ├── JsonTreeWriter.java │ │ │ ├── MapTypeAdapterFactory.java │ │ │ ├── ObjectTypeAdapter.java │ │ │ ├── ReflectiveTypeAdapterFactory.java │ │ │ ├── SqlDateTypeAdapter.java │ │ │ ├── TimeTypeAdapter.java │ │ │ ├── TreeTypeAdapter.java │ │ │ ├── TypeAdapterRuntimeTypeWrapper.java │ │ │ ├── TypeAdapters.java │ │ │ └── util │ │ │ │ └── ISO8601Utils.java │ │ └── package-info.java │ │ ├── package-info.java │ │ ├── reflect │ │ ├── TypeToken.java │ │ └── package-info.java │ │ └── stream │ │ ├── JsonReader.java │ │ ├── JsonScope.java │ │ ├── JsonToken.java │ │ ├── JsonWriter.java │ │ └── MalformedJsonException.java │ └── test │ └── java │ └── com │ └── google │ └── gson │ ├── CommentsTest.java │ ├── DefaultDateTypeAdapterTest.java │ ├── DefaultInetAddressTypeAdapterTest.java │ ├── DefaultMapJsonSerializerTest.java │ ├── ExposeAnnotationExclusionStrategyTest.java │ ├── FieldAttributesTest.java │ ├── GenericArrayTypeTest.java │ ├── GsonBuilderTest.java │ ├── GsonTest.java │ ├── GsonTypeAdapterTest.java │ ├── InnerClassExclusionStrategyTest.java │ ├── JavaSerializationTest.java │ ├── JsonArrayTest.java │ ├── JsonNullTest.java │ ├── JsonObjectTest.java │ ├── JsonParserTest.java │ ├── JsonPrimitiveTest.java │ ├── JsonStreamParserTest.java │ ├── LongSerializationPolicyTest.java │ ├── MixedStreamTest.java │ ├── MockExclusionStrategy.java │ ├── ObjectTypeAdapterTest.java │ ├── OverrideCoreTypeAdaptersTest.java │ ├── ParameterizedTypeFixtures.java │ ├── ParameterizedTypeTest.java │ ├── PrimitiveTypeAdapter.java │ ├── VersionExclusionStrategyTest.java │ ├── common │ ├── MoreAsserts.java │ └── TestTypes.java │ ├── functional │ ├── ArrayTest.java │ ├── CircularReferenceTest.java │ ├── CollectionTest.java │ ├── ConcurrencyTest.java │ ├── CustomDeserializerTest.java │ ├── CustomSerializerTest.java │ ├── CustomTypeAdaptersTest.java │ ├── DefaultTypeAdaptersTest.java │ ├── DelegateTypeAdapterTest.java │ ├── EnumTest.java │ ├── EscapingTest.java │ ├── ExclusionStrategyFunctionalTest.java │ ├── ExposeFieldsTest.java │ ├── FieldExclusionTest.java │ ├── FieldNamingTest.java │ ├── InheritanceTest.java │ ├── InstanceCreatorTest.java │ ├── InterfaceTest.java │ ├── InternationalizationTest.java │ ├── JavaUtilConcurrentAtomicTest.java │ ├── JavaUtilTest.java │ ├── JsonAdapterAnnotationOnClassesTest.java │ ├── JsonAdapterAnnotationOnFieldsTest.java │ ├── JsonAdapterSerializerDeserializerTest.java │ ├── JsonArrayTest.java │ ├── JsonParserTest.java │ ├── JsonTreeTest.java │ ├── LeniencyTest.java │ ├── MapAsArrayTypeAdapterTest.java │ ├── MapTest.java │ ├── MoreSpecificTypeSerializationTest.java │ ├── NamingPolicyTest.java │ ├── NullObjectAndFieldTest.java │ ├── ObjectTest.java │ ├── ParameterizedTypesTest.java │ ├── PrettyPrintingTest.java │ ├── PrimitiveCharacterTest.java │ ├── PrimitiveTest.java │ ├── PrintFormattingTest.java │ ├── RawSerializationTest.java │ ├── ReadersWritersTest.java │ ├── RuntimeTypeAdapterFactoryFunctionalTest.java │ ├── SecurityTest.java │ ├── SerializedNameTest.java │ ├── StreamingTypeAdaptersTest.java │ ├── StringTest.java │ ├── ThrowableFunctionalTest.java │ ├── TreeTypeAdaptersTest.java │ ├── TypeAdapterPrecedenceTest.java │ ├── TypeHierarchyAdapterTest.java │ ├── TypeVariableTest.java │ ├── UncategorizedTest.java │ └── VersioningTest.java │ ├── internal │ ├── GsonTypesTest.java │ ├── LazilyParsedNumberTest.java │ ├── LinkedHashTreeMapTest.java │ ├── LinkedTreeMapTest.java │ ├── UnsafeAllocatorInstantiationTest.java │ └── bind │ │ ├── JsonElementReaderTest.java │ │ ├── JsonTreeReaderTest.java │ │ ├── JsonTreeWriterTest.java │ │ └── RecursiveTypesResolveTest.java │ ├── metrics │ └── PerformanceTest.java │ ├── reflect │ └── TypeTokenTest.java │ ├── regression │ └── JsonAdapterNullSafeTest.java │ └── stream │ ├── JsonReaderPathTest.java │ ├── JsonReaderTest.java │ └── JsonWriterTest.java ├── lib ├── gson-cleanup-styles.xml └── gson-formatting-styles.xml ├── metrics ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── google │ └── gson │ └── metrics │ ├── BagOfPrimitives.java │ ├── BagOfPrimitivesDeserializationBenchmark.java │ ├── CollectionsDeserializationBenchmark.java │ ├── ParseBenchmark.java │ ├── ParseBenchmarkData.zip │ └── SerializationBenchmark.java ├── pom.xml └── proto ├── .gitignore ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── google │ │ └── gson │ │ └── protobuf │ │ └── ProtoTypeAdapter.java └── protobuf │ ├── annotations.proto │ └── bag.proto └── test └── java └── com └── google └── gson └── protobuf └── functional ├── ProtosWithAnnotationsTest.java ├── ProtosWithComplexAndRepeatedFieldsTest.java └── ProtosWithPrimitiveTypesTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | .classpath 2 | .project 3 | .settings 4 | eclipsebin 5 | target 6 | */target 7 | pom.xml.* 8 | release.properties 9 | 10 | .idea 11 | *.iml 12 | *.ipr 13 | *.iws 14 | classes 15 | 16 | .DS_Store 17 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | 3 | jdk: 4 | - oraclejdk7 5 | - oraclejdk8 6 | 7 | install: mvn -f gson install -DskipTests=true 8 | script: mvn -f gson test 9 | 10 | branches: 11 | except: 12 | - gh-pages 13 | 14 | notifications: 15 | email: false 16 | 17 | sudo: false 18 | 19 | cache: 20 | directories: 21 | - $HOME/.m2 22 | -------------------------------------------------------------------------------- /codegen/src/main/java/com/google/gson/codegen/CodeGen.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 Square, Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson.codegen; 18 | 19 | import javax.lang.model.element.Element; 20 | import javax.lang.model.element.ElementKind; 21 | import javax.lang.model.element.PackageElement; 22 | import javax.lang.model.element.TypeElement; 23 | 24 | public class CodeGen { 25 | private CodeGen() { 26 | } 27 | 28 | public static PackageElement getPackage(Element type) { 29 | while (type.getKind() != ElementKind.PACKAGE) { 30 | type = type.getEnclosingElement(); 31 | } 32 | return (PackageElement) type; 33 | } 34 | 35 | /** 36 | * Returns a fully qualified class name to complement {@code type}. 37 | */ 38 | public static String adapterName(TypeElement typeElement, String suffix) { 39 | StringBuilder builder = new StringBuilder(); 40 | rawTypeToString(builder, typeElement, '$'); 41 | builder.append(suffix); 42 | return builder.toString(); 43 | } 44 | 45 | static void rawTypeToString(StringBuilder result, TypeElement type, char innerClassSeparator) { 46 | String packageName = getPackage(type).getQualifiedName().toString(); 47 | String qualifiedName = type.getQualifiedName().toString(); 48 | result.append(packageName); 49 | result.append('.'); 50 | result.append( 51 | qualifiedName.substring(packageName.length() + 1).replace('.', innerClassSeparator)); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /codegen/src/main/java/com/google/gson/codegen/GeneratedTypeAdapter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson.codegen; 18 | 19 | public @interface GeneratedTypeAdapter { 20 | Class[] value() default {}; 21 | } 22 | -------------------------------------------------------------------------------- /codegen/src/main/java/com/google/gson/codegen/GeneratedTypeAdapterProcessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson.codegen; 18 | 19 | import static java.lang.reflect.Modifier.FINAL; 20 | 21 | import java.io.IOException; 22 | import java.util.Set; 23 | 24 | import javax.annotation.processing.AbstractProcessor; 25 | import javax.annotation.processing.RoundEnvironment; 26 | import javax.annotation.processing.SupportedAnnotationTypes; 27 | import javax.annotation.processing.SupportedSourceVersion; 28 | import javax.lang.model.SourceVersion; 29 | import javax.lang.model.element.Element; 30 | import javax.lang.model.element.TypeElement; 31 | import javax.tools.Diagnostic; 32 | import javax.tools.JavaFileObject; 33 | 34 | @SupportedAnnotationTypes("com.google.gson.codegen.GeneratedTypeAdapter") 35 | @SupportedSourceVersion(SourceVersion.RELEASE_6) 36 | public final class GeneratedTypeAdapterProcessor extends AbstractProcessor { 37 | @Override public boolean process(Set types, RoundEnvironment env) { 38 | System.out.println("invoked GeneratedTypeAdapterProcessor"); 39 | try { 40 | for (Element element : env.getElementsAnnotatedWith(GeneratedTypeAdapter.class)) { 41 | writeAdapter((TypeElement) element); 42 | } 43 | } catch (IOException e) { 44 | processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage()); 45 | } 46 | return true; 47 | } 48 | 49 | private void writeAdapter(TypeElement type) throws IOException { 50 | String typeAdapterName = CodeGen.adapterName(type, "$TypeAdapter"); 51 | JavaFileObject sourceFile = processingEnv.getFiler() 52 | .createSourceFile(typeAdapterName, type); 53 | System.out.println("Generating type adapter: " + typeAdapterName + " in " + sourceFile.getName()); 54 | 55 | JavaWriter writer = new JavaWriter(sourceFile.openWriter()); 56 | writer.addPackage(CodeGen.getPackage(type).getQualifiedName().toString()); 57 | writer.beginType(typeAdapterName, "class", FINAL, null); 58 | writer.endType(); 59 | writer.close(); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /codegen/src/main/resources/META-INF/services/javax.annotation.processing.Processor: -------------------------------------------------------------------------------- 1 | com.google.gson.codegen.GeneratedTypeAdapterProcessor -------------------------------------------------------------------------------- /codegen/src/test/java/com/google/gson/codegen/functional/CodeGenFunctionalTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.gson.codegen.functional; 17 | 18 | import junit.framework.TestCase; 19 | 20 | public class CodeGenFunctionalTest extends TestCase { 21 | 22 | public void testGeneratedJson() { 23 | Order order = new Order("toy", 10); 24 | // TODO: figure out how to access the generated type adapter 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /codegen/src/test/java/com/google/gson/codegen/functional/Order.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.gson.codegen.functional; 17 | 18 | import com.google.gson.codegen.GeneratedTypeAdapter; 19 | 20 | @GeneratedTypeAdapter 21 | final class Order { 22 | private final String itemName; 23 | private final int price; 24 | 25 | public Order(String itemName, int price) { 26 | this.itemName = itemName; 27 | this.price = price; 28 | } 29 | 30 | public String getItemName() { 31 | return itemName; 32 | } 33 | 34 | public int getAmount() { 35 | return price; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /examples/android-proguard-example/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /examples/android-proguard-example/default.properties: -------------------------------------------------------------------------------- 1 | # This file is automatically generated by Android Tools. 2 | # Do not modify this file -- YOUR CHANGES WILL BE ERASED! 3 | # 4 | # This file must be checked in Version Control Systems. 5 | # 6 | # To customize properties used by the Ant build system use, 7 | # "build.properties", and override values to adapt the script to your 8 | # project structure. 9 | 10 | # Project target. 11 | target=android-3 12 | proguard.config=proguard.cfg -------------------------------------------------------------------------------- /examples/android-proguard-example/proguard.cfg: -------------------------------------------------------------------------------- 1 | ##---------------Begin: proguard configuration for Gson ---------- 2 | # Gson uses generic type information stored in a class file when working with fields. Proguard 3 | # removes such information by default, so configure it to keep all of it. 4 | -keepattributes Signature 5 | 6 | # For using GSON @Expose annotation 7 | -keepattributes *Annotation* 8 | 9 | # Gson specific classes 10 | -keep class sun.misc.Unsafe { *; } 11 | #-keep class com.google.gson.stream.** { *; } 12 | 13 | # Application classes that will be serialized/deserialized over Gson 14 | -keep class com.google.gson.examples.android.model.** { *; } 15 | 16 | # Prevent proguard from stripping interface information from TypeAdapterFactory, 17 | # JsonSerializer, JsonDeserializer instances (so they can be used in @JsonAdapter) 18 | -keep class * implements com.google.gson.TypeAdapterFactory 19 | -keep class * implements com.google.gson.JsonSerializer 20 | -keep class * implements com.google.gson.JsonDeserializer 21 | 22 | ##---------------End: proguard configuration for Gson ---------- 23 | -------------------------------------------------------------------------------- /examples/android-proguard-example/res/drawable/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YangLang116/IKGson/5873a9632b7462000545afd766e0d1085850ae49/examples/android-proguard-example/res/drawable/icon.png -------------------------------------------------------------------------------- /examples/android-proguard-example/res/layout/main.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 9 | 12 | -------------------------------------------------------------------------------- /examples/android-proguard-example/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | Gson Proguard Example 4 | 5 | 6 | -------------------------------------------------------------------------------- /examples/android-proguard-example/src/com/google/gson/examples/android/GsonProguardExampleActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.gson.examples.android; 17 | 18 | import java.util.ArrayList; 19 | import java.util.List; 20 | 21 | import android.app.Activity; 22 | import android.os.Bundle; 23 | import android.widget.TextView; 24 | 25 | import com.google.gson.Gson; 26 | import com.google.gson.examples.android.model.Cart; 27 | import com.google.gson.examples.android.model.LineItem; 28 | 29 | /** 30 | * Activity class illustrating how to use proguard with Gson 31 | * 32 | * @author Inderjeet Singh 33 | */ 34 | public class GsonProguardExampleActivity extends Activity { 35 | @Override 36 | public void onCreate(Bundle icicle) { 37 | super.onCreate(icicle); 38 | setContentView(R.layout.main); 39 | TextView tv = (TextView) findViewById(R.id.tv); 40 | Gson gson = new Gson(); 41 | Cart cart = buildCart(); 42 | StringBuilder sb = new StringBuilder(); 43 | sb.append("Gson.toJson() example: \n"); 44 | sb.append(" Cart Object: ").append(cart).append("\n"); 45 | sb.append(" Cart JSON: ").append(gson.toJson(cart)).append("\n"); 46 | sb.append("\n\nGson.fromJson() example: \n"); 47 | String json = "{buyer:'Happy Camper',creditCard:'4111-1111-1111-1111'," 48 | + "lineItems:[{name:'nails',priceInMicros:100000,quantity:100,currencyCode:'USD'}]}"; 49 | sb.append("Cart JSON: ").append(json).append("\n"); 50 | sb.append("Cart Object: ").append(gson.fromJson(json, Cart.class)).append("\n"); 51 | tv.setText(sb.toString()); 52 | tv.invalidate(); 53 | } 54 | 55 | private Cart buildCart() { 56 | List lineItems = new ArrayList(); 57 | lineItems.add(new LineItem("hammer", 1, 12000000, "USD")); 58 | return new Cart(lineItems, "Happy Buyer", "4111-1111-1111-1111"); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /examples/android-proguard-example/src/com/google/gson/examples/android/model/Cart.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.gson.examples.android.model; 17 | 18 | import java.lang.reflect.ParameterizedType; 19 | import java.lang.reflect.Type; 20 | import java.lang.reflect.WildcardType; 21 | import java.util.List; 22 | 23 | import com.google.gson.annotations.SerializedName; 24 | 25 | /** 26 | * A model object representing a cart that can be posted to an order-processing server 27 | * 28 | * @author Inderjeet Singh 29 | */ 30 | public class Cart { 31 | public final List lineItems; 32 | 33 | @SerializedName("buyer") 34 | private final String buyerName; 35 | 36 | private final String creditCard; 37 | 38 | public Cart(List lineItems, String buyerName, String creditCard) { 39 | this.lineItems = lineItems; 40 | this.buyerName = buyerName; 41 | this.creditCard = creditCard; 42 | } 43 | 44 | public List getLineItems() { 45 | return lineItems; 46 | } 47 | 48 | public String getBuyerName() { 49 | return buyerName; 50 | } 51 | 52 | public String getCreditCard() { 53 | return creditCard; 54 | } 55 | 56 | @Override 57 | public String toString() { 58 | StringBuilder itemsText = new StringBuilder(); 59 | boolean first = true; 60 | if (lineItems != null) { 61 | try { 62 | Class fieldType = Cart.class.getField("lineItems").getType(); 63 | System.out.println("LineItems CLASS: " + getSimpleTypeName(fieldType)); 64 | } catch (SecurityException e) { 65 | } catch (NoSuchFieldException e) { 66 | } 67 | for (LineItem item : lineItems) { 68 | if (first) { 69 | first = false; 70 | } else { 71 | itemsText.append("; "); 72 | } 73 | itemsText.append(item); 74 | } 75 | } 76 | return "[BUYER: " + buyerName + "; CC: " + creditCard + "; " 77 | + "LINE_ITEMS: " + itemsText.toString() + "]"; 78 | } 79 | 80 | @SuppressWarnings("unchecked") 81 | public static String getSimpleTypeName(Type type) { 82 | if (type == null) { 83 | return "null"; 84 | } 85 | if (type instanceof Class) { 86 | return ((Class)type).getSimpleName(); 87 | } else if (type instanceof ParameterizedType) { 88 | ParameterizedType pType = (ParameterizedType) type; 89 | StringBuilder sb = new StringBuilder(getSimpleTypeName(pType.getRawType())); 90 | sb.append('<'); 91 | boolean first = true; 92 | for (Type argumentType : pType.getActualTypeArguments()) { 93 | if (first) { 94 | first = false; 95 | } else { 96 | sb.append(','); 97 | } 98 | sb.append(getSimpleTypeName(argumentType)); 99 | } 100 | sb.append('>'); 101 | return sb.toString(); 102 | } else if (type instanceof WildcardType) { 103 | return "?"; 104 | } 105 | return type.toString(); 106 | } 107 | 108 | } 109 | -------------------------------------------------------------------------------- /examples/android-proguard-example/src/com/google/gson/examples/android/model/LineItem.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.gson.examples.android.model; 17 | 18 | /** 19 | * A line item in a cart. This is not a rest resource, just a dependent object 20 | * 21 | * @author Inderjeet Singh 22 | */ 23 | public class LineItem { 24 | private final String name; 25 | private final int quantity; 26 | private final long priceInMicros; 27 | private final String currencyCode; 28 | 29 | public LineItem(String name, int quantity, long priceInMicros, String currencyCode) { 30 | this.name = name; 31 | this.quantity = quantity; 32 | this.priceInMicros = priceInMicros; 33 | this.currencyCode = currencyCode; 34 | } 35 | 36 | public String getName() { 37 | return name; 38 | } 39 | 40 | public int getQuantity() { 41 | return quantity; 42 | } 43 | 44 | public long getPriceInMicros() { 45 | return priceInMicros; 46 | } 47 | 48 | public String getCurrencyCode() { 49 | return currencyCode; 50 | } 51 | 52 | @Override 53 | public String toString() { 54 | return String.format("(item: %s, qty: %s, price: %.2f %s)", 55 | name, quantity, priceInMicros / 1000000d, currencyCode); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /extras/src/main/java/com/google/gson/extras/examples/rawcollections/RawCollectionsExample.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.gson.extras.examples.rawcollections; 17 | 18 | import java.util.ArrayList; 19 | import java.util.Collection; 20 | 21 | import com.google.gson.Gson; 22 | import com.google.gson.JsonArray; 23 | import com.google.gson.JsonParser; 24 | 25 | public class RawCollectionsExample { 26 | static class Event { 27 | private String name; 28 | private String source; 29 | private Event(String name, String source) { 30 | this.name = name; 31 | this.source = source; 32 | } 33 | @Override 34 | public String toString() { 35 | return String.format("(name=%s, source=%s)", name, source); 36 | } 37 | } 38 | 39 | @SuppressWarnings({ "unchecked", "rawtypes" }) 40 | public static void main(String[] args) { 41 | Gson gson = new Gson(); 42 | Collection collection = new ArrayList(); 43 | collection.add("hello"); 44 | collection.add(5); 45 | collection.add(new Event("GREETINGS", "guest")); 46 | String json = gson.toJson(collection); 47 | System.out.println("Using Gson.toJson() on a raw collection: " + json); 48 | JsonParser parser = new JsonParser(); 49 | JsonArray array = parser.parse(json).getAsJsonArray(); 50 | String message = gson.fromJson(array.get(0), String.class); 51 | int number = gson.fromJson(array.get(1), int.class); 52 | Event event = gson.fromJson(array.get(2), Event.class); 53 | System.out.printf("Using Gson.fromJson() to get: %s, %d, %s", message, number, event); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /extras/src/main/java/com/google/gson/interceptors/Intercept.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson.interceptors; 18 | 19 | import java.lang.annotation.ElementType; 20 | import java.lang.annotation.Retention; 21 | import java.lang.annotation.RetentionPolicy; 22 | import java.lang.annotation.Target; 23 | 24 | 25 | /** 26 | * Use this annotation to indicate various interceptors for class instances after 27 | * they have been processed by Gson. For example, you can use it to validate an instance 28 | * after it has been deserialized from Json. 29 | * Here is an example of how this annotation is used: 30 | *

Here is an example of how this annotation is used: 31 | *

32 |  * @Intercept(postDeserialize=UserValidator.class)
33 |  * public class User {
34 |  *   String name;
35 |  *   String password;
36 |  *   String emailAddress;
37 |  * }
38 |  *
39 |  * public class UserValidator implements JsonPostDeserializer<User> {
40 |  *   public void postDeserialize(User user) {
41 |  *     // Do some checks on user
42 |  *     if (user.name == null || user.password == null) {
43 |  *       throw new JsonParseException("name and password are required fields.");
44 |  *     }
45 |  *     if (user.emailAddress == null) {
46 |  *       emailAddress = "unknown"; // assign a default value.
47 |  *     }
48 |  *   }
49 |  * }
50 |  * 

51 | * 52 | * @author Inderjeet Singh 53 | */ 54 | @Retention(RetentionPolicy.RUNTIME) 55 | @Target(ElementType.TYPE) 56 | public @interface Intercept { 57 | 58 | /** 59 | * Specify the class that provides the methods that should be invoked after an instance 60 | * has been deserialized. 61 | */ 62 | @SuppressWarnings("rawtypes") 63 | public Class postDeserialize(); 64 | } 65 | -------------------------------------------------------------------------------- /extras/src/main/java/com/google/gson/interceptors/InterceptorFactory.java: -------------------------------------------------------------------------------- 1 | package com.google.gson.interceptors; 2 | 3 | import com.google.gson.Gson; 4 | import com.google.gson.TypeAdapter; 5 | import com.google.gson.TypeAdapterFactory; 6 | import com.google.gson.reflect.TypeToken; 7 | import com.google.gson.stream.JsonReader; 8 | import com.google.gson.stream.JsonWriter; 9 | import java.io.IOException; 10 | 11 | /** 12 | * A type adapter factory that implements {@code @Intercept}. 13 | */ 14 | public final class InterceptorFactory implements TypeAdapterFactory { 15 | public TypeAdapter create(Gson gson, TypeToken type) { 16 | Intercept intercept = type.getRawType().getAnnotation(Intercept.class); 17 | if (intercept == null) { 18 | return null; 19 | } 20 | 21 | TypeAdapter delegate = gson.getDelegateAdapter(this, type); 22 | return new InterceptorAdapter(delegate, intercept); 23 | } 24 | 25 | static class InterceptorAdapter extends TypeAdapter { 26 | private final TypeAdapter delegate; 27 | private final JsonPostDeserializer postDeserializer; 28 | 29 | @SuppressWarnings("unchecked") // ? 30 | public InterceptorAdapter(TypeAdapter delegate, Intercept intercept) { 31 | try { 32 | this.delegate = delegate; 33 | this.postDeserializer = intercept.postDeserialize().newInstance(); 34 | } catch (Exception e) { 35 | throw new RuntimeException(e); 36 | } 37 | } 38 | 39 | @Override public void write(JsonWriter out, T value) throws IOException { 40 | delegate.write(out, value); 41 | } 42 | 43 | @Override public T read(JsonReader in) throws IOException { 44 | T result = delegate.read(in); 45 | postDeserializer.postDeserialize(result); 46 | return result; 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /extras/src/main/java/com/google/gson/interceptors/JsonPostDeserializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.gson.interceptors; 17 | 18 | import com.google.gson.InstanceCreator; 19 | 20 | /** 21 | * This interface is implemented by a class that wishes to inspect or modify an object 22 | * after it has been deserialized. You must define a no-args constructor or register an 23 | * {@link InstanceCreator} for such a class. 24 | * 25 | * @author Inderjeet Singh 26 | */ 27 | public interface JsonPostDeserializer { 28 | 29 | /** 30 | * This method is called by Gson after the object has been deserialized from Json. 31 | */ 32 | public void postDeserialize(T object); 33 | } 34 | -------------------------------------------------------------------------------- /extras/src/main/java/com/google/gson/typeadapters/PostConstructAdapterFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Gson Authors 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson.typeadapters; 18 | 19 | import java.io.IOException; 20 | import java.lang.reflect.InvocationTargetException; 21 | import java.lang.reflect.Method; 22 | 23 | import javax.annotation.PostConstruct; 24 | 25 | import com.google.gson.Gson; 26 | import com.google.gson.TypeAdapter; 27 | import com.google.gson.TypeAdapterFactory; 28 | import com.google.gson.reflect.TypeToken; 29 | import com.google.gson.stream.JsonReader; 30 | import com.google.gson.stream.JsonWriter; 31 | 32 | public class PostConstructAdapterFactory implements TypeAdapterFactory { 33 | // copied from https://gist.github.com/swankjesse/20df26adaf639ed7fd160f145a0b661a 34 | @Override 35 | public TypeAdapter create(Gson gson, TypeToken type) { 36 | for (Class t = type.getRawType(); (t != Object.class) && (t.getSuperclass() != null); t = t.getSuperclass()) { 37 | for (Method m : t.getDeclaredMethods()) { 38 | if (m.isAnnotationPresent(PostConstruct.class)) { 39 | m.setAccessible(true); 40 | TypeAdapter delegate = gson.getDelegateAdapter(this, type); 41 | return new PostConstructAdapter(delegate, m); 42 | } 43 | } 44 | } 45 | return null; 46 | } 47 | 48 | final static class PostConstructAdapter extends TypeAdapter { 49 | private final TypeAdapter delegate; 50 | private final Method method; 51 | 52 | public PostConstructAdapter(TypeAdapter delegate, Method method) { 53 | this.delegate = delegate; 54 | this.method = method; 55 | } 56 | 57 | @Override public T read(JsonReader in) throws IOException { 58 | T result = delegate.read(in); 59 | if (result != null) { 60 | try { 61 | method.invoke(result); 62 | } catch (IllegalAccessException e) { 63 | throw new AssertionError(); 64 | } catch (InvocationTargetException e) { 65 | if (e.getCause() instanceof RuntimeException) throw (RuntimeException) e.getCause(); 66 | throw new RuntimeException(e.getCause()); 67 | } 68 | } 69 | return result; 70 | } 71 | 72 | @Override public void write(JsonWriter out, T value) throws IOException { 73 | delegate.write(out, value); 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /extras/src/test/java/com/google/gson/typeadapters/UtcDateTypeAdapterTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson.typeadapters; 18 | 19 | import java.text.SimpleDateFormat; 20 | import java.util.Calendar; 21 | import java.util.Date; 22 | import java.util.Locale; 23 | import java.util.TimeZone; 24 | 25 | import com.google.gson.JsonParseException; 26 | import junit.framework.TestCase; 27 | 28 | import com.google.gson.Gson; 29 | import com.google.gson.GsonBuilder; 30 | 31 | public final class UtcDateTypeAdapterTest extends TestCase { 32 | private final Gson gson = new GsonBuilder() 33 | .registerTypeAdapter(Date.class, new UtcDateTypeAdapter()) 34 | .create(); 35 | 36 | public void testLocalTimeZone() { 37 | Date expected = new Date(); 38 | String json = gson.toJson(expected); 39 | Date actual = gson.fromJson(json, Date.class); 40 | assertEquals(expected.getTime(), actual.getTime()); 41 | } 42 | 43 | public void testDifferentTimeZones() { 44 | for (String timeZone : TimeZone.getAvailableIDs()) { 45 | Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(timeZone)); 46 | Date expected = cal.getTime(); 47 | String json = gson.toJson(expected); 48 | // System.out.println(json + ": " + timeZone); 49 | Date actual = gson.fromJson(json, Date.class); 50 | assertEquals(expected.getTime(), actual.getTime()); 51 | } 52 | } 53 | 54 | /** 55 | * JDK 1.7 introduced support for XXX format to indicate UTC date. But Android is older JDK. 56 | * We want to make sure that this date is parseable in Android. 57 | */ 58 | public void testUtcDatesOnJdkBefore1_7() { 59 | Gson gson = new GsonBuilder() 60 | .registerTypeAdapter(Date.class, new UtcDateTypeAdapter()) 61 | .create(); 62 | gson.fromJson("'2014-12-05T04:00:00.000Z'", Date.class); 63 | } 64 | 65 | public void testUtcWithJdk7Default() { 66 | Date expected = new Date(); 67 | SimpleDateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.US); 68 | iso8601Format.setTimeZone(TimeZone.getTimeZone("UTC")); 69 | String expectedJson = "\"" + iso8601Format.format(expected) + "\""; 70 | String actualJson = gson.toJson(expected); 71 | assertEquals(expectedJson, actualJson); 72 | Date actual = gson.fromJson(expectedJson, Date.class); 73 | assertEquals(expected.getTime(), actual.getTime()); 74 | } 75 | 76 | public void testNullDateSerialization() { 77 | String json = gson.toJson(null, Date.class); 78 | assertEquals("null", json); 79 | } 80 | 81 | public void testWellFormedParseException() { 82 | try { 83 | gson.fromJson("2017-06-20T14:32:30", Date.class); 84 | fail("No exception"); 85 | } catch (JsonParseException exe) { 86 | assertEquals(exe.getMessage(), "java.text.ParseException: Failed to parse date ['2017-06-20T14']: 2017-06-20T14"); 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /gson/Gson 2.1 notes.txt: -------------------------------------------------------------------------------- 1 | Dropped support for GsonBuilder.registerTypeHierarchyAdapter+InstanceCreator 2 | 3 | Relax registerTypeHierarchyAdapter order 4 | Gson 2.0 failed if you registered Manager then Employee would fail 5 | Gson 2.1 it isn't a problem 6 | com.google.gson.functional.TypeHierarchyAdapterTest#testRegisterSubTypeFirstNotAllowed -------------------------------------------------------------------------------- /gson/IKGson.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YangLang116/IKGson/5873a9632b7462000545afd766e0d1085850ae49/gson/IKGson.jar -------------------------------------------------------------------------------- /gson/README: -------------------------------------------------------------------------------- 1 | Gson is a Java library that can be used to convert a Java object into its 2 | JSON representation. It can also be used to convert a JSON string into an 3 | equivalent Java object. Gson can work with arbitrary Java objects including 4 | pre-existing objects that you do not have source-code of. 5 | 6 | Complete Gson documentation is available at its project page 7 | https://github.com/google/gson 8 | -------------------------------------------------------------------------------- /gson/assembly-descriptor.xml: -------------------------------------------------------------------------------- 1 | 2 | release 3 | 4 | zip 5 | 6 | 7 | 8 | 9 | README* 10 | LICENSE* 11 | 12 | 13 | 14 | target 15 | 16 | 17 | gson-*.jar 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /gson/bnd.bnd: -------------------------------------------------------------------------------- 1 | Bundle-SymbolicName: com.google.gson 2 | Bundle-Name: ${project.name} 3 | Bundle-Description: ${project.description} 4 | Bundle-Vendor: Google Gson Project 5 | Bundle-ContactAddress: ${project.parent.url} 6 | Bundle-RequiredExecutionEnvironment: J2SE-1.5, JavaSE-1.6, JavaSE-1.7, JavaSE-1.8 7 | 8 | -removeheaders: Private-Package 9 | 10 | -exportcontents:\ 11 | com.google.gson,\ 12 | com.google.gson.annotations,\ 13 | com.google.gson.reflect,\ 14 | com.google.gson.stream 15 | -------------------------------------------------------------------------------- /gson/docs/javadocs/com/google/gson/annotations/package-frame.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | com.google.gson.annotations (Gson 2.3.1 API) 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | com.google.gson.annotations 21 | 22 | 23 | 36 | 37 |
24 | Annotation Types  25 | 26 |
27 | Expose 28 |
29 | JsonAdapter 30 |
31 | SerializedName 32 |
33 | Since 34 |
35 | Until
38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /gson/docs/javadocs/com/google/gson/reflect/package-frame.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | com.google.gson.reflect (Gson 2.3.1 API) 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | com.google.gson.reflect 21 | 22 | 23 | 28 | 29 |
24 | Classes  25 | 26 |
27 | TypeToken
30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /gson/docs/javadocs/com/google/gson/stream/package-frame.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | com.google.gson.stream (Gson 2.3.1 API) 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | com.google.gson.stream 21 | 22 | 23 | 30 | 31 |
24 | Classes  25 | 26 |
27 | JsonReader 28 |
29 | JsonWriter
32 | 33 | 34 | 35 | 36 | 41 | 42 |
37 | Enums  38 | 39 |
40 | JsonToken
43 | 44 | 45 | 46 | 47 | 52 | 53 |
48 | Exceptions  49 | 50 |
51 | MalformedJsonException
54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /gson/docs/javadocs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Gson 2.3.1 API 9 | 10 | 55 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | <H2> 66 | Frame Alert</H2> 67 | 68 | <P> 69 | This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. 70 | <BR> 71 | Link to<A HREF="overview-summary.html">Non-frame version.</A> 72 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /gson/docs/javadocs/overview-frame.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Overview List (Gson 2.3.1 API) 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 24 | 25 |
23 |
26 | 27 | 28 | 29 | 43 | 44 |
All Classes 30 |

31 | 32 | Packages 33 |
34 | com.google.gson 35 |
36 | com.google.gson.annotations 37 |
38 | com.google.gson.reflect 39 |
40 | com.google.gson.stream 41 |
42 |

45 | 46 |

47 |   48 | 49 | 50 | -------------------------------------------------------------------------------- /gson/docs/javadocs/package-list: -------------------------------------------------------------------------------- 1 | com.google.gson 2 | com.google.gson.annotations 3 | com.google.gson.reflect 4 | com.google.gson.stream 5 | -------------------------------------------------------------------------------- /gson/docs/javadocs/resources/inherit.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YangLang116/IKGson/5873a9632b7462000545afd766e0d1085850ae49/gson/docs/javadocs/resources/inherit.gif -------------------------------------------------------------------------------- /gson/docs/javadocs/script.js: -------------------------------------------------------------------------------- 1 | function show(type) 2 | { 3 | count = 0; 4 | for (var key in methods) { 5 | var row = document.getElementById(key); 6 | if ((methods[key] & type) != 0) { 7 | row.style.display = ''; 8 | row.className = (count++ % 2) ? rowColor : altColor; 9 | } 10 | else 11 | row.style.display = 'none'; 12 | } 13 | updateTabs(type); 14 | } 15 | 16 | function updateTabs(type) 17 | { 18 | for (var value in tabs) { 19 | var sNode = document.getElementById(tabs[value][0]); 20 | var spanNode = sNode.firstChild; 21 | if (value == type) { 22 | sNode.className = activeTableTab; 23 | spanNode.innerHTML = tabs[value][1]; 24 | } 25 | else { 26 | sNode.className = tableTab; 27 | spanNode.innerHTML = "" + tabs[value][1] + ""; 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /gson/docs/javadocs/stylesheet.css: -------------------------------------------------------------------------------- 1 | /* Javadoc style sheet */ 2 | 3 | /* Define colors, fonts and other style attributes here to override the defaults */ 4 | 5 | /* Page background color */ 6 | body { background-color: #FFFFFF; color:#000000 } 7 | 8 | /* Headings */ 9 | h1 { font-size: 145% } 10 | 11 | /* Table colors */ 12 | .TableHeadingColor { background: #CCCCFF; color:#000000 } /* Dark mauve */ 13 | .TableSubHeadingColor { background: #EEEEFF; color:#000000 } /* Light mauve */ 14 | .TableRowColor { background: #FFFFFF; color:#000000 } /* White */ 15 | 16 | /* Font used in left-hand frame lists */ 17 | .FrameTitleFont { font-size: 100%; font-family: Helvetica, Arial, sans-serif; color:#000000 } 18 | .FrameHeadingFont { font-size: 90%; font-family: Helvetica, Arial, sans-serif; color:#000000 } 19 | .FrameItemFont { font-size: 90%; font-family: Helvetica, Arial, sans-serif; color:#000000 } 20 | 21 | /* Navigation bar fonts and colors */ 22 | .NavBarCell1 { background-color:#EEEEFF; color:#000000} /* Light mauve */ 23 | .NavBarCell1Rev { background-color:#00008B; color:#FFFFFF} /* Dark Blue */ 24 | .NavBarFont1 { font-family: Arial, Helvetica, sans-serif; color:#000000;color:#000000;} 25 | .NavBarFont1Rev { font-family: Arial, Helvetica, sans-serif; color:#FFFFFF;color:#FFFFFF;} 26 | 27 | .NavBarCell2 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF; color:#000000} 28 | .NavBarCell3 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF; color:#000000} 29 | 30 | -------------------------------------------------------------------------------- /gson/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | 4 | 5 | com.google.code.gson 6 | gson-parent 7 | 2.8.2-SNAPSHOT 8 | 9 | 10 | gson 11 | Gson 12 | 13 | 14 | 15 | junit 16 | junit 17 | test 18 | 19 | 20 | 21 | 22 | 23 | 24 | org.apache.maven.plugins 25 | maven-javadoc-plugin 26 | 27 | com.google.gson 28 | com.google.gson.internal:com.google.gson.internal.bind 29 | 30 | http://docs.oracle.com/javase/6/docs/api/ 31 | 32 | 33 | 34 | 35 | biz.aQute.bnd 36 | bnd-maven-plugin 37 | 3.1.0 38 | 39 | 40 | 41 | bnd-process 42 | 43 | 44 | 45 | 46 | 47 | org.apache.maven.plugins 48 | maven-jar-plugin 49 | 50 | 51 | ${project.build.outputDirectory}/META-INF/MANIFEST.MF 52 | 53 | 54 | 55 | 56 | org.apache.felix 57 | maven-bundle-plugin 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /gson/src/main/java/com/google/gson/FieldNamingStrategy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson; 18 | 19 | import java.lang.reflect.Field; 20 | 21 | /** 22 | * A mechanism for providing custom field naming in Gson. This allows the client code to translate 23 | * field names into a particular convention that is not supported as a normal Java field 24 | * declaration rules. For example, Java does not support "-" characters in a field name. 25 | * 26 | * @author Inderjeet Singh 27 | * @author Joel Leitch 28 | * @since 1.3 29 | */ 30 | public interface FieldNamingStrategy { 31 | 32 | /** 33 | * Translates the field name into its JSON field name representation. 34 | * 35 | * @param f the field object that we are translating 36 | * @return the translated field name. 37 | * @since 1.3 38 | */ 39 | public String translateName(Field f); 40 | } 41 | -------------------------------------------------------------------------------- /gson/src/main/java/com/google/gson/JsonDeserializationContext.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson; 18 | 19 | import java.lang.reflect.Type; 20 | 21 | /** 22 | * Context for deserialization that is passed to a custom deserializer during invocation of its 23 | * {@link JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext)} 24 | * method. 25 | * 26 | * @author Inderjeet Singh 27 | * @author Joel Leitch 28 | */ 29 | public interface JsonDeserializationContext { 30 | 31 | /** 32 | * Invokes default deserialization on the specified object. It should never be invoked on 33 | * the element received as a parameter of the 34 | * {@link JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext)} method. Doing 35 | * so will result in an infinite loop since Gson will in-turn call the custom deserializer again. 36 | * 37 | * @param json the parse tree. 38 | * @param typeOfT type of the expected return value. 39 | * @param The type of the deserialized object. 40 | * @return An object of type typeOfT. 41 | * @throws JsonParseException if the parse tree does not contain expected data. 42 | */ 43 | public T deserialize(JsonElement json, Type typeOfT) throws JsonParseException; 44 | } -------------------------------------------------------------------------------- /gson/src/main/java/com/google/gson/JsonIOException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.gson; 17 | 18 | /** 19 | * This exception is raised when Gson was unable to read an input stream 20 | * or write to one. 21 | * 22 | * @author Inderjeet Singh 23 | * @author Joel Leitch 24 | */ 25 | public final class JsonIOException extends JsonParseException { 26 | private static final long serialVersionUID = 1L; 27 | 28 | public JsonIOException(String msg) { 29 | super(msg); 30 | } 31 | 32 | public JsonIOException(String msg, Throwable cause) { 33 | super(msg, cause); 34 | } 35 | 36 | /** 37 | * Creates exception with the specified cause. Consider using 38 | * {@link #JsonIOException(String, Throwable)} instead if you can describe what happened. 39 | * 40 | * @param cause root exception that caused this exception to be thrown. 41 | */ 42 | public JsonIOException(Throwable cause) { 43 | super(cause); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /gson/src/main/java/com/google/gson/JsonNull.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson; 18 | 19 | /** 20 | * A class representing a Json {@code null} value. 21 | * 22 | * @author Inderjeet Singh 23 | * @author Joel Leitch 24 | * @since 1.2 25 | */ 26 | public final class JsonNull extends JsonElement { 27 | /** 28 | * singleton for JsonNull 29 | * 30 | * @since 1.8 31 | */ 32 | public static final JsonNull INSTANCE = new JsonNull(); 33 | 34 | /** 35 | * Creates a new JsonNull object. 36 | * Deprecated since Gson version 1.8. Use {@link #INSTANCE} instead 37 | */ 38 | @Deprecated 39 | public JsonNull() { 40 | // Do nothing 41 | } 42 | 43 | /** 44 | * Returns the same instance since it is an immutable value 45 | * @since 2.8.2 46 | */ 47 | @Override 48 | public JsonNull deepCopy() { 49 | return INSTANCE; 50 | } 51 | 52 | /** 53 | * All instances of JsonNull have the same hash code since they are indistinguishable 54 | */ 55 | @Override 56 | public int hashCode() { 57 | return JsonNull.class.hashCode(); 58 | } 59 | 60 | /** 61 | * All instances of JsonNull are the same 62 | */ 63 | @Override 64 | public boolean equals(Object other) { 65 | return this == other || other instanceof JsonNull; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /gson/src/main/java/com/google/gson/JsonParseException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson; 18 | 19 | /** 20 | * This exception is raised if there is a serious issue that occurs during parsing of a Json 21 | * string. One of the main usages for this class is for the Gson infrastructure. If the incoming 22 | * Json is bad/malicious, an instance of this exception is raised. 23 | * 24 | *

This exception is a {@link RuntimeException} because it is exposed to the client. Using a 25 | * {@link RuntimeException} avoids bad coding practices on the client side where they catch the 26 | * exception and do nothing. It is often the case that you want to blow up if there is a parsing 27 | * error (i.e. often clients do not know how to recover from a {@link JsonParseException}.

28 | * 29 | * @author Inderjeet Singh 30 | * @author Joel Leitch 31 | */ 32 | public class JsonParseException extends RuntimeException { 33 | static final long serialVersionUID = -4086729973971783390L; 34 | 35 | /** 36 | * Creates exception with the specified message. If you are wrapping another exception, consider 37 | * using {@link #JsonParseException(String, Throwable)} instead. 38 | * 39 | * @param msg error message describing a possible cause of this exception. 40 | */ 41 | public JsonParseException(String msg) { 42 | super(msg); 43 | } 44 | 45 | /** 46 | * Creates exception with the specified message and cause. 47 | * 48 | * @param msg error message describing what happened. 49 | * @param cause root exception that caused this exception to be thrown. 50 | */ 51 | public JsonParseException(String msg, Throwable cause) { 52 | super(msg, cause); 53 | } 54 | 55 | /** 56 | * Creates exception with the specified cause. Consider using 57 | * {@link #JsonParseException(String, Throwable)} instead if you can describe what happened. 58 | * 59 | * @param cause root exception that caused this exception to be thrown. 60 | */ 61 | public JsonParseException(Throwable cause) { 62 | super(cause); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /gson/src/main/java/com/google/gson/JsonParser.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2009 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.gson; 17 | 18 | import java.io.IOException; 19 | import java.io.Reader; 20 | import java.io.StringReader; 21 | 22 | import com.google.gson.internal.Streams; 23 | import com.google.gson.stream.JsonReader; 24 | import com.google.gson.stream.JsonToken; 25 | import com.google.gson.stream.MalformedJsonException; 26 | 27 | /** 28 | * A parser to parse Json into a parse tree of {@link JsonElement}s 29 | * 30 | * @author Inderjeet Singh 31 | * @author Joel Leitch 32 | * @since 1.3 33 | */ 34 | public final class JsonParser { 35 | 36 | /** 37 | * Parses the specified JSON string into a parse tree 38 | * 39 | * @param json JSON text 40 | * @return a parse tree of {@link JsonElement}s corresponding to the specified JSON 41 | * @throws JsonParseException if the specified text is not valid JSON 42 | * @since 1.3 43 | */ 44 | public JsonElement parse(String json) throws JsonSyntaxException { 45 | return parse(new StringReader(json)); 46 | } 47 | 48 | /** 49 | * Parses the specified JSON string into a parse tree 50 | * 51 | * @param json JSON text 52 | * @return a parse tree of {@link JsonElement}s corresponding to the specified JSON 53 | * @throws JsonParseException if the specified text is not valid JSON 54 | * @since 1.3 55 | */ 56 | public JsonElement parse(Reader json) throws JsonIOException, JsonSyntaxException { 57 | try { 58 | JsonReader jsonReader = new JsonReader(json); 59 | JsonElement element = parse(jsonReader); 60 | if (!element.isJsonNull() && jsonReader.peek() != JsonToken.END_DOCUMENT) { 61 | throw new JsonSyntaxException("Did not consume the entire document."); 62 | } 63 | return element; 64 | } catch (MalformedJsonException e) { 65 | throw new JsonSyntaxException(e); 66 | } catch (IOException e) { 67 | throw new JsonIOException(e); 68 | } catch (NumberFormatException e) { 69 | throw new JsonSyntaxException(e); 70 | } 71 | } 72 | 73 | /** 74 | * Returns the next value from the JSON stream as a parse tree. 75 | * 76 | * @throws JsonParseException if there is an IOException or if the specified 77 | * text is not valid JSON 78 | * @since 1.6 79 | */ 80 | public JsonElement parse(JsonReader json) throws JsonIOException, JsonSyntaxException { 81 | boolean lenient = json.isLenient(); 82 | json.setLenient(true); 83 | try { 84 | return Streams.parse(json); 85 | } catch (StackOverflowError e) { 86 | throw new JsonParseException("Failed parsing JSON source: " + json + " to Json", e); 87 | } catch (OutOfMemoryError e) { 88 | throw new JsonParseException("Failed parsing JSON source: " + json + " to Json", e); 89 | } finally { 90 | json.setLenient(lenient); 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /gson/src/main/java/com/google/gson/JsonSerializationContext.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson; 18 | 19 | import java.lang.reflect.Type; 20 | 21 | /** 22 | * Context for serialization that is passed to a custom serializer during invocation of its 23 | * {@link JsonSerializer#serialize(Object, Type, JsonSerializationContext)} method. 24 | * 25 | * @author Inderjeet Singh 26 | * @author Joel Leitch 27 | */ 28 | public interface JsonSerializationContext { 29 | 30 | /** 31 | * Invokes default serialization on the specified object. 32 | * 33 | * @param src the object that needs to be serialized. 34 | * @return a tree of {@link JsonElement}s corresponding to the serialized form of {@code src}. 35 | */ 36 | public JsonElement serialize(Object src); 37 | 38 | /** 39 | * Invokes default serialization on the specified object passing the specific type information. 40 | * It should never be invoked on the element received as a parameter of the 41 | * {@link JsonSerializer#serialize(Object, Type, JsonSerializationContext)} method. Doing 42 | * so will result in an infinite loop since Gson will in-turn call the custom serializer again. 43 | * 44 | * @param src the object that needs to be serialized. 45 | * @param typeOfSrc the actual genericized type of src object. 46 | * @return a tree of {@link JsonElement}s corresponding to the serialized form of {@code src}. 47 | */ 48 | public JsonElement serialize(Object src, Type typeOfSrc); 49 | } 50 | -------------------------------------------------------------------------------- /gson/src/main/java/com/google/gson/JsonSyntaxException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2010 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.gson; 17 | 18 | /** 19 | * This exception is raised when Gson attempts to read (or write) a malformed 20 | * JSON element. 21 | * 22 | * @author Inderjeet Singh 23 | * @author Joel Leitch 24 | */ 25 | public final class JsonSyntaxException extends JsonParseException { 26 | 27 | private static final long serialVersionUID = 1L; 28 | 29 | public JsonSyntaxException(String msg) { 30 | super(msg); 31 | } 32 | 33 | public JsonSyntaxException(String msg, Throwable cause) { 34 | super(msg, cause); 35 | } 36 | 37 | /** 38 | * Creates exception with the specified cause. Consider using 39 | * {@link #JsonSyntaxException(String, Throwable)} instead if you can 40 | * describe what actually happened. 41 | * 42 | * @param cause root exception that caused this exception to be thrown. 43 | */ 44 | public JsonSyntaxException(Throwable cause) { 45 | super(cause); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /gson/src/main/java/com/google/gson/LongSerializationPolicy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2009 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson; 18 | 19 | /** 20 | * Defines the expected format for a {@code long} or {@code Long} type when its serialized. 21 | * 22 | * @since 1.3 23 | * 24 | * @author Inderjeet Singh 25 | * @author Joel Leitch 26 | */ 27 | public enum LongSerializationPolicy { 28 | /** 29 | * This is the "default" serialization policy that will output a {@code long} object as a JSON 30 | * number. For example, assume an object has a long field named "f" then the serialized output 31 | * would be: 32 | * {@code {"f":123}}. 33 | */ 34 | DEFAULT() { 35 | @Override public JsonElement serialize(Long value) { 36 | return new JsonPrimitive(value); 37 | } 38 | }, 39 | 40 | /** 41 | * Serializes a long value as a quoted string. For example, assume an object has a long field 42 | * named "f" then the serialized output would be: 43 | * {@code {"f":"123"}}. 44 | */ 45 | STRING() { 46 | @Override public JsonElement serialize(Long value) { 47 | return new JsonPrimitive(String.valueOf(value)); 48 | } 49 | }; 50 | 51 | /** 52 | * Serialize this {@code value} using this serialization policy. 53 | * 54 | * @param value the long value to be serialized into a {@link JsonElement} 55 | * @return the serialized version of {@code value} 56 | */ 57 | public abstract JsonElement serialize(Long value); 58 | } 59 | -------------------------------------------------------------------------------- /gson/src/main/java/com/google/gson/annotations/SerializedName.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson.annotations; 18 | 19 | import java.lang.annotation.Documented; 20 | import java.lang.annotation.ElementType; 21 | import java.lang.annotation.Retention; 22 | import java.lang.annotation.RetentionPolicy; 23 | import java.lang.annotation.Target; 24 | 25 | /** 26 | * An annotation that indicates this member should be serialized to JSON with 27 | * the provided name value as its field name. 28 | * 29 | *

This annotation will override any {@link com.google.gson.FieldNamingPolicy}, including 30 | * the default field naming policy, that may have been set on the {@link com.google.gson.Gson} 31 | * instance. A different naming policy can set using the {@code GsonBuilder} class. See 32 | * {@link com.google.gson.GsonBuilder#setFieldNamingPolicy(com.google.gson.FieldNamingPolicy)} 33 | * for more information.

34 | * 35 | *

Here is an example of how this annotation is meant to be used:

36 | *
37 |  * public class MyClass {
38 |  *   @SerializedName("name") String a;
39 |  *   @SerializedName(value="name1", alternate={"name2", "name3"}) String b;
40 |  *   String c;
41 |  *
42 |  *   public MyClass(String a, String b, String c) {
43 |  *     this.a = a;
44 |  *     this.b = b;
45 |  *     this.c = c;
46 |  *   }
47 |  * }
48 |  * 
49 | * 50 | *

The following shows the output that is generated when serializing an instance of the 51 | * above example class:

52 | *
53 |  * MyClass target = new MyClass("v1", "v2", "v3");
54 |  * Gson gson = new Gson();
55 |  * String json = gson.toJson(target);
56 |  * System.out.println(json);
57 |  *
58 |  * ===== OUTPUT =====
59 |  * {"name":"v1","name1":"v2","c":"v3"}
60 |  * 
61 | * 62 | *

NOTE: The value you specify in this annotation must be a valid JSON field name.

63 | * While deserializing, all values specified in the annotation will be deserialized into the field. 64 | * For example: 65 | *
66 |  *   MyClass target = gson.fromJson("{'name1':'v1'}", MyClass.class);
67 |  *   assertEquals("v1", target.b);
68 |  *   target = gson.fromJson("{'name2':'v2'}", MyClass.class);
69 |  *   assertEquals("v2", target.b);
70 |  *   target = gson.fromJson("{'name3':'v3'}", MyClass.class);
71 |  *   assertEquals("v3", target.b);
72 |  * 
73 | * Note that MyClass.b is now deserialized from either name1, name2 or name3. 74 | * 75 | * @see com.google.gson.FieldNamingPolicy 76 | * 77 | * @author Inderjeet Singh 78 | * @author Joel Leitch 79 | */ 80 | @Documented 81 | @Retention(RetentionPolicy.RUNTIME) 82 | @Target({ElementType.FIELD, ElementType.METHOD}) 83 | public @interface SerializedName { 84 | 85 | /** 86 | * @return the desired name of the field when it is serialized or deserialized 87 | */ 88 | String value(); 89 | /** 90 | * @return the alternative names of the field when it is deserialized 91 | */ 92 | String[] alternate() default {}; 93 | } 94 | -------------------------------------------------------------------------------- /gson/src/main/java/com/google/gson/annotations/Since.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson.annotations; 18 | 19 | import java.lang.annotation.Documented; 20 | import java.lang.annotation.ElementType; 21 | import java.lang.annotation.Retention; 22 | import java.lang.annotation.RetentionPolicy; 23 | import java.lang.annotation.Target; 24 | 25 | /** 26 | * An annotation that indicates the version number since a member or a type has been present. 27 | * This annotation is useful to manage versioning of your Json classes for a web-service. 28 | * 29 | *

30 | * This annotation has no effect unless you build {@link com.google.gson.Gson} with a 31 | * {@link com.google.gson.GsonBuilder} and invoke 32 | * {@link com.google.gson.GsonBuilder#setVersion(double)} method. 33 | * 34 | *

Here is an example of how this annotation is meant to be used:

35 | *
36 |  * public class User {
37 |  *   private String firstName;
38 |  *   private String lastName;
39 |  *   @Since(1.0) private String emailAddress;
40 |  *   @Since(1.0) private String password;
41 |  *   @Since(1.1) private Address address;
42 |  * }
43 |  * 
44 | * 45 | *

If you created Gson with {@code new Gson()}, the {@code toJson()} and {@code fromJson()} 46 | * methods will use all the fields for serialization and deserialization. However, if you created 47 | * Gson with {@code Gson gson = new GsonBuilder().setVersion(1.0).create()} then the 48 | * {@code toJson()} and {@code fromJson()} methods of Gson will exclude the {@code address} field 49 | * since it's version number is set to {@code 1.1}.

50 | * 51 | * @author Inderjeet Singh 52 | * @author Joel Leitch 53 | */ 54 | @Documented 55 | @Retention(RetentionPolicy.RUNTIME) 56 | @Target({ElementType.FIELD, ElementType.TYPE}) 57 | public @interface Since { 58 | /** 59 | * the value indicating a version number since this member 60 | * or type has been present. 61 | */ 62 | double value(); 63 | } 64 | -------------------------------------------------------------------------------- /gson/src/main/java/com/google/gson/annotations/Until.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson.annotations; 18 | 19 | import java.lang.annotation.Documented; 20 | import java.lang.annotation.ElementType; 21 | import java.lang.annotation.Retention; 22 | import java.lang.annotation.RetentionPolicy; 23 | import java.lang.annotation.Target; 24 | 25 | /** 26 | * An annotation that indicates the version number until a member or a type should be present. 27 | * Basically, if Gson is created with a version number that exceeds the value stored in the 28 | * {@code Until} annotation then the field will be ignored from the JSON output. This annotation 29 | * is useful to manage versioning of your JSON classes for a web-service. 30 | * 31 | *

32 | * This annotation has no effect unless you build {@link com.google.gson.Gson} with a 33 | * {@link com.google.gson.GsonBuilder} and invoke 34 | * {@link com.google.gson.GsonBuilder#setVersion(double)} method. 35 | * 36 | *

Here is an example of how this annotation is meant to be used:

37 | *
38 |  * public class User {
39 |  *   private String firstName;
40 |  *   private String lastName;
41 |  *   @Until(1.1) private String emailAddress;
42 |  *   @Until(1.1) private String password;
43 |  * }
44 |  * 
45 | * 46 | *

If you created Gson with {@code new Gson()}, the {@code toJson()} and {@code fromJson()} 47 | * methods will use all the fields for serialization and deserialization. However, if you created 48 | * Gson with {@code Gson gson = new GsonBuilder().setVersion(1.2).create()} then the 49 | * {@code toJson()} and {@code fromJson()} methods of Gson will exclude the {@code emailAddress} 50 | * and {@code password} fields from the example above, because the version number passed to the 51 | * GsonBuilder, {@code 1.2}, exceeds the version number set on the {@code Until} annotation, 52 | * {@code 1.1}, for those fields. 53 | * 54 | * @author Inderjeet Singh 55 | * @author Joel Leitch 56 | * @since 1.3 57 | */ 58 | @Documented 59 | @Retention(RetentionPolicy.RUNTIME) 60 | @Target({ElementType.FIELD, ElementType.TYPE}) 61 | public @interface Until { 62 | 63 | /** 64 | * the value indicating a version number until this member 65 | * or type should be ignored. 66 | */ 67 | double value(); 68 | } 69 | -------------------------------------------------------------------------------- /gson/src/main/java/com/google/gson/annotations/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * This package provides annotations that can be used with {@link com.google.gson.Gson}. 3 | * 4 | * @author Inderjeet Singh, Joel Leitch 5 | */ 6 | package com.google.gson.annotations; -------------------------------------------------------------------------------- /gson/src/main/java/com/google/gson/internal/$Gson$Preconditions.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson.internal; 18 | 19 | /** 20 | * A simple utility class used to check method Preconditions. 21 | * 22 | *

23 |  * public long divideBy(long value) {
24 |  *   Preconditions.checkArgument(value != 0);
25 |  *   return this.value / value;
26 |  * }
27 |  * 
28 | * 29 | * @author Inderjeet Singh 30 | * @author Joel Leitch 31 | */ 32 | public final class $Gson$Preconditions { 33 | private $Gson$Preconditions() { 34 | throw new UnsupportedOperationException(); 35 | } 36 | 37 | public static T checkNotNull(T obj) { 38 | if (obj == null) { 39 | throw new NullPointerException(); 40 | } 41 | return obj; 42 | } 43 | 44 | public static void checkArgument(boolean condition) { 45 | if (!condition) { 46 | throw new IllegalArgumentException(); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /gson/src/main/java/com/google/gson/internal/JsonReaderInternalAccess.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson.internal; 18 | 19 | import com.google.gson.stream.JsonReader; 20 | import java.io.IOException; 21 | 22 | /** 23 | * Internal-only APIs of JsonReader available only to other classes in Gson. 24 | */ 25 | public abstract class JsonReaderInternalAccess { 26 | public static JsonReaderInternalAccess INSTANCE; 27 | 28 | /** 29 | * Changes the type of the current property name token to a string value. 30 | */ 31 | public abstract void promoteNameToValue(JsonReader reader) throws IOException; 32 | } 33 | -------------------------------------------------------------------------------- /gson/src/main/java/com/google/gson/internal/LazilyParsedNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.gson.internal; 17 | 18 | import java.io.ObjectStreamException; 19 | import java.math.BigDecimal; 20 | 21 | /** 22 | * This class holds a number value that is lazily converted to a specific number type 23 | * 24 | * @author Inderjeet Singh 25 | */ 26 | public final class LazilyParsedNumber extends Number { 27 | private final String value; 28 | 29 | /** @param value must not be null */ 30 | public LazilyParsedNumber(String value) { 31 | this.value = value; 32 | } 33 | 34 | @Override 35 | public int intValue() { 36 | try { 37 | return Integer.parseInt(value); 38 | } catch (NumberFormatException e) { 39 | try { 40 | return (int) Long.parseLong(value); 41 | } catch (NumberFormatException nfe) { 42 | return new BigDecimal(value).intValue(); 43 | } 44 | } 45 | } 46 | 47 | @Override 48 | public long longValue() { 49 | try { 50 | return Long.parseLong(value); 51 | } catch (NumberFormatException e) { 52 | return new BigDecimal(value).longValue(); 53 | } 54 | } 55 | 56 | @Override 57 | public float floatValue() { 58 | return Float.parseFloat(value); 59 | } 60 | 61 | @Override 62 | public double doubleValue() { 63 | return Double.parseDouble(value); 64 | } 65 | 66 | @Override 67 | public String toString() { 68 | return value; 69 | } 70 | 71 | /** 72 | * If somebody is unlucky enough to have to serialize one of these, serialize 73 | * it as a BigDecimal so that they won't need Gson on the other side to 74 | * deserialize it. 75 | */ 76 | private Object writeReplace() throws ObjectStreamException { 77 | return new BigDecimal(value); 78 | } 79 | 80 | @Override 81 | public int hashCode() { 82 | return value.hashCode(); 83 | } 84 | 85 | @Override 86 | public boolean equals(Object obj) { 87 | if (this == obj) { 88 | return true; 89 | } 90 | if (obj instanceof LazilyParsedNumber) { 91 | LazilyParsedNumber other = (LazilyParsedNumber) obj; 92 | return value == other.value || value.equals(other.value); 93 | } 94 | return false; 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /gson/src/main/java/com/google/gson/internal/ObjectConstructor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson.internal; 18 | 19 | /** 20 | * Defines a generic object construction factory. The purpose of this class 21 | * is to construct a default instance of a class that can be used for object 22 | * navigation while deserialization from its JSON representation. 23 | * 24 | * @author Inderjeet Singh 25 | * @author Joel Leitch 26 | */ 27 | public interface ObjectConstructor { 28 | 29 | /** 30 | * Returns a new instance. 31 | */ 32 | public T construct(); 33 | } -------------------------------------------------------------------------------- /gson/src/main/java/com/google/gson/internal/bind/DateTypeAdapter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson.internal.bind; 18 | 19 | import com.google.gson.Gson; 20 | import com.google.gson.JsonSyntaxException; 21 | import com.google.gson.TypeAdapter; 22 | import com.google.gson.TypeAdapterFactory; 23 | import com.google.gson.internal.bind.util.ISO8601Utils; 24 | import com.google.gson.reflect.TypeToken; 25 | import com.google.gson.stream.JsonReader; 26 | import com.google.gson.stream.JsonToken; 27 | import com.google.gson.stream.JsonWriter; 28 | import java.io.IOException; 29 | import java.text.DateFormat; 30 | import java.text.ParseException; 31 | import java.text.ParsePosition; 32 | import java.util.Date; 33 | import java.util.Locale; 34 | 35 | /** 36 | * Adapter for Date. Although this class appears stateless, it is not. 37 | * DateFormat captures its time zone and locale when it is created, which gives 38 | * this class state. DateFormat isn't thread safe either, so this class has 39 | * to synchronize its read and write methods. 40 | */ 41 | public final class DateTypeAdapter extends TypeAdapter { 42 | public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() { 43 | @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal 44 | @Override public TypeAdapter create(Gson gson, TypeToken typeToken) { 45 | return typeToken.getRawType() == Date.class ? (TypeAdapter) new DateTypeAdapter() : null; 46 | } 47 | }; 48 | 49 | private final DateFormat enUsFormat 50 | = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.US); 51 | private final DateFormat localFormat 52 | = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT); 53 | 54 | @Override public Date read(JsonReader in) throws IOException { 55 | if (in.peek() == JsonToken.NULL) { 56 | in.nextNull(); 57 | return null; 58 | } 59 | return deserializeToDate(in.nextString()); 60 | } 61 | 62 | private synchronized Date deserializeToDate(String json) { 63 | try { 64 | return localFormat.parse(json); 65 | } catch (ParseException ignored) { 66 | } 67 | try { 68 | return enUsFormat.parse(json); 69 | } catch (ParseException ignored) { 70 | } 71 | try { 72 | return ISO8601Utils.parse(json, new ParsePosition(0)); 73 | } catch (ParseException e) { 74 | throw new JsonSyntaxException(json, e); 75 | } 76 | } 77 | 78 | @Override public synchronized void write(JsonWriter out, Date value) throws IOException { 79 | if (value == null) { 80 | out.nullValue(); 81 | return; 82 | } 83 | String dateFormatAsString = enUsFormat.format(value); 84 | out.value(dateFormatAsString); 85 | } 86 | 87 | 88 | } 89 | -------------------------------------------------------------------------------- /gson/src/main/java/com/google/gson/internal/bind/ObjectTypeAdapter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson.internal.bind; 18 | 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; 27 | 28 | import java.io.IOException; 29 | import java.util.ArrayList; 30 | import java.util.List; 31 | import java.util.Map; 32 | 33 | /** 34 | * Adapts types whose static type is only 'Object'. Uses getClass() on 35 | * serialization and a primitive/Map/List on deserialization. 36 | */ 37 | public final class ObjectTypeAdapter extends TypeAdapter { 38 | public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() { 39 | @SuppressWarnings("unchecked") 40 | @Override public TypeAdapter create(Gson gson, TypeToken type) { 41 | if (type.getRawType() == Object.class) { 42 | return (TypeAdapter) new ObjectTypeAdapter(gson); 43 | } 44 | return null; 45 | } 46 | }; 47 | 48 | private final Gson gson; 49 | 50 | ObjectTypeAdapter(Gson gson) { 51 | this.gson = gson; 52 | } 53 | 54 | @Override public Object read(JsonReader in) throws IOException { 55 | JsonToken token = in.peek(); 56 | switch (token) { 57 | case BEGIN_ARRAY: 58 | List list = new ArrayList(); 59 | in.beginArray(); 60 | while (in.hasNext()) { 61 | list.add(read(in)); 62 | } 63 | in.endArray(); 64 | return list; 65 | 66 | case BEGIN_OBJECT: 67 | Map map = new LinkedTreeMap(); 68 | in.beginObject(); 69 | while (in.hasNext()) { 70 | map.put(in.nextName(), read(in)); 71 | } 72 | in.endObject(); 73 | return map; 74 | 75 | case STRING: 76 | return in.nextString(); 77 | 78 | case NUMBER: 79 | return in.nextDouble(); 80 | 81 | case BOOLEAN: 82 | return in.nextBoolean(); 83 | 84 | case NULL: 85 | in.nextNull(); 86 | return null; 87 | 88 | default: 89 | throw new IllegalStateException(); 90 | } 91 | } 92 | 93 | @SuppressWarnings("unchecked") 94 | @Override public void write(JsonWriter out, Object value) throws IOException { 95 | if (value == null) { 96 | out.nullValue(); 97 | return; 98 | } 99 | 100 | TypeAdapter typeAdapter = (TypeAdapter) gson.getAdapter(value.getClass()); 101 | if (typeAdapter instanceof ObjectTypeAdapter) { 102 | out.beginObject(); 103 | out.endObject(); 104 | return; 105 | } 106 | 107 | typeAdapter.write(out, value); 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /gson/src/main/java/com/google/gson/internal/bind/SqlDateTypeAdapter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson.internal.bind; 18 | 19 | import com.google.gson.Gson; 20 | import com.google.gson.JsonSyntaxException; 21 | import com.google.gson.TypeAdapter; 22 | import com.google.gson.TypeAdapterFactory; 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; 27 | import java.io.IOException; 28 | import java.text.DateFormat; 29 | import java.text.ParseException; 30 | import java.text.SimpleDateFormat; 31 | 32 | /** 33 | * Adapter for java.sql.Date. Although this class appears stateless, it is not. 34 | * DateFormat captures its time zone and locale when it is created, which gives 35 | * this class state. DateFormat isn't thread safe either, so this class has 36 | * to synchronize its read and write methods. 37 | */ 38 | public final class SqlDateTypeAdapter extends TypeAdapter { 39 | public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() { 40 | @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal 41 | @Override public TypeAdapter create(Gson gson, TypeToken typeToken) { 42 | return typeToken.getRawType() == java.sql.Date.class 43 | ? (TypeAdapter) new SqlDateTypeAdapter() : null; 44 | } 45 | }; 46 | 47 | private final DateFormat format = new SimpleDateFormat("MMM d, yyyy"); 48 | 49 | @Override 50 | public synchronized java.sql.Date read(JsonReader in) throws IOException { 51 | if (in.peek() == JsonToken.NULL) { 52 | in.nextNull(); 53 | return null; 54 | } 55 | try { 56 | final long utilDate = format.parse(in.nextString()).getTime(); 57 | return new java.sql.Date(utilDate); 58 | } catch (ParseException e) { 59 | throw new JsonSyntaxException(e); 60 | } 61 | } 62 | 63 | @Override 64 | public synchronized void write(JsonWriter out, java.sql.Date value) throws IOException { 65 | out.value(value == null ? null : format.format(value)); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /gson/src/main/java/com/google/gson/internal/bind/TimeTypeAdapter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Google Inc. 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, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson.internal.bind; 18 | 19 | import com.google.gson.Gson; 20 | import com.google.gson.JsonSyntaxException; 21 | import com.google.gson.TypeAdapter; 22 | import com.google.gson.TypeAdapterFactory; 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; 27 | import java.io.IOException; 28 | import java.sql.Time; 29 | import java.text.DateFormat; 30 | import java.text.ParseException; 31 | import java.text.SimpleDateFormat; 32 | import java.util.Date; 33 | 34 | /** 35 | * Adapter for Time. Although this class appears stateless, it is not. 36 | * DateFormat captures its time zone and locale when it is created, which gives 37 | * this class state. DateFormat isn't thread safe either, so this class has 38 | * to synchronize its read and write methods. 39 | */ 40 | public final class TimeTypeAdapter extends TypeAdapter