pax_global_header00006660000000000000000000000064131603435160014514gustar00rootroot0000000000000052 comment=d90f63dc88ac08971cf088a3537e1b1108603574 gson-gson-parent-2.8.2/000077500000000000000000000000001316034351600147265ustar00rootroot00000000000000gson-gson-parent-2.8.2/.gitignore000066400000000000000000000002021316034351600167100ustar00rootroot00000000000000.classpath .project .settings eclipsebin target */target pom.xml.* release.properties .idea *.iml *.ipr *.iws classes .DS_Store gson-gson-parent-2.8.2/.travis.yml000066400000000000000000000003621316034351600170400ustar00rootroot00000000000000language: java jdk: - oraclejdk7 - oraclejdk8 install: mvn -f gson install -DskipTests=true script: mvn -f gson test branches: except: - gh-pages notifications: email: false sudo: false cache: directories: - $HOME/.m2 gson-gson-parent-2.8.2/CHANGELOG.md000066400000000000000000000370251316034351600165460ustar00rootroot00000000000000Change Log ========== ## Version 2.8.2 _2017-09-19_ [GitHub Diff](https://github.com/google/gson/compare/gson-parent-2.8.1...gson-parent-2.8.2) * Introduced a new API, `JsonElement.deepCopy()` * Numerous other bugfixes ## Version 2.8.1 _2017-05-30_ [GitHub Diff](https://github.com/google/gson/compare/gson-parent-2.8.0...gson-parent-2.8.1) * New: `JsonObject.keySet()` * `@JsonAdapter` annotation can now use `JsonSerializer` and `JsonDeserializer` as well. ## Version 2.8 _2016-10-26_ [GitHub Diff](https://github.com/google/gson/compare/gson-parent-2.7...gson-parent-2.8.0) * New: `TypeToken.getParameterized()` and `TypeToken.getArray()` make it easier to register or look up a `TypeAdapter`. * New: `@JsonAdapter(nullSafe=true)` to specify that a custom type adapter handles null. ## Version 2.7 _2016-06-14_ [GitHub Diff](https://github.com/google/gson/compare/gson-parent-2.6.2...gson-parent-2.7) * Added support for JsonSerializer/JsonDeserializer in @JsonAdapter annotation * Exposing Gson properties excluder(), fieldNamingStrategy(), serializeNulls(), htmlSafe() * Added JsonObject.size() method * Added JsonWriter.value(Boolean value) method * Using ArrayDeque, ConcurrentHashMap, and other JDK 1.6 features * Better error reporting * Plenty of other bug fixes ## Version 2.6.2 _2016-02-26_ [GitHub Diff](https://github.com/google/gson/compare/gson-parent-2.6.1...gson-parent-2.6.2) * Fixed an NPE bug with @JsonAdapter annotation * Added back OSGI manifest * Some documentation typo fixes ## Version 2.6.1 _2016-02-11_ [GitHub Diff](https://github.com/google/gson/compare/gson-parent-2.6...gson-parent-2.6.1) * Fix: The 2.6 release targeted Java 1.7, but we intend to target Java 1.6. The 2.6.1 release is identical to 2.6, but it targets Java 1.6. ## Version 2.6 _2016-02-11_ [GitHub Diff](https://github.com/google/gson/compare/gson-parent-2.5...gson-parent-2.6) * Permit timezones without minutes in the default date adapter. * Update reader and writer for RFC 7159. This means that strings, numbers, booleans and null may be top-level values in JSON documents, even if the reader is strict. * New `setLenient()` method on `GsonBuilder`. This setting impacts the new factory method `Gson.newJsonReader()`. * Adapters discovered with `@JsonAdapter` are now null safe by default. ## Version 2.5 _2015-11-24_ [GitHub Diff](https://github.com/google/gson/compare/gson-parent-2.4...gson-parent-2.5) * Updated minimum JDK version to 1.6 * Improved Date Deserialization by accepting many date formats * Added support for `java.util.Currency`, `AtomicLong`, `AtomicLongArray`, `AtomicInteger`, `AtomicIntegerArray`, `AtomicBoolean`. This change is backward-incompatible because the earlier version of Gson used the default serialization which wasn't intuitive. We hope that these classes are not used enough to actually cause problems in the field. * Improved debugging information when some exceptions are thrown ## Version 2.4 _2015-10-04_ * **Drop `IOException` from `TypeAdapter.toJson()`.** This is a binary-compatible change, but may cause compiler errors where `IOExceptions` are being caught but no longer thrown. The correct fix for this problem is to remove the unnecessary `catch` clause. * New: `Gson.newJsonWriter` method returns configured `JsonWriter` instances. * New: `@SerializedName` now works with [AutoValue’s][autovalue] abstract property methods. * New: `@SerializedName` permits alternate names when deserializing. * New: `JsonWriter#jsonValue` writes raw JSON values. * New: APIs to add primitives directly to `JsonArray` instances. * New: ISO 8601 date type adapter. Find this in _extras_. * Fix: `FieldNamingPolicy` now works properly when running on a device with a Turkish locale. [autovalue]: https://github.com/google/auto/tree/master/value ## Version 2.3.1 _2014-11-20_ * Added support to serialize objects with self-referential fields. The self-referential field is set to null in JSON. Previous version of Gson threw a StackOverflowException on encountering any self-referential fields. * The most visible impact of this is that Gson can now serialize Throwable (Exception and Error) * Added support for @JsonAdapter annotation on enums which are user defined types * Fixed bug in getPath() with array of objects and arrays of arrays * Other smaller bug fixes ## Version 2.3 _2014-08-11_ * The new @JsonAdapter annotation to specify a Json TypeAdapter for a class field * JsonPath support: JsonReader.getPath() method returns the JsonPath expression * New public methods in JsonArray (similar to the java.util.List): `contains(JsonElement), remove(JsonElement), remove(int index), set(int index, JsonElement element)` * Many other smaller bug fixes ## Version 2.2.4 _2013-05-13_ * Fix internal map (LinkedHashTreeMap) hashing bug. * Bug fix (Issue 511) ## Version 2.2.3 _2013-04-12_ * Fixes for possible DoS attack due to poor String hashing ## Version 2.2.2 _2012-07-02_ * Gson now allows a user to override default type adapters for Primitives and Strings. This behavior was allowed in earlier versions of Gson but was prohibited started Gson 2.0. We decided to allow it again: This enables a user to parse 1/0 as boolean values for compatibility with iOS JSON libraries. * (Incompatible behavior change in `JsonParser`): In the past, if `JsonParser` encountered a stream that terminated prematurely, it returned `JsonNull`. This behavior wasn't correct because the stream had invalid JSON, not a null. `JsonParser` is now changed to throw `JsonSyntaxException` in this case. Note that if JsonParser (or Gson) encounter an empty stream, they still return `JsonNull`. ## Version 2.2.1 _2012-05-05_ * Very minor fixes ## Version 2.2 _2012-05-05_ * Added getDelegateAdapter in Gson class * Fixed a security bug related to denial of service attack with Java HashMap String collisions. ## Version 2.1 _2011-12-30_ (Targeted Dec 31, 2011) * Support for user-defined streaming type adapters * continued performance enhancements * Dropped support for type hierarchy instance creators. We don't expect this to be a problem. We'll also detect fewer errors where multiple type adapters can serialize the same type. With APIs like getNextTypeAdapter, this might actually be an improvement! ## Version 2.0 _2011-11-13_ #### Faster * Previous versions first parsed complete document into a DOM-style model (JsonObject or JsonArray) and then bound data against that. Gson 2 does data binding directly from the stream parser. #### More Predictable * Objects are serialized and deserialized in the same way, regardless of where they occur in the object graph. #### Changes to watch out for * Gson 1.7 would serialize top-level nulls as "". 2.0 serializes them as "null". ``` String json = gson.toJson(null, Foo.class); 1.7: json == "" 2.0: json == "null" ``` * Gson 1.7 permitted duplicate map keys. 2.0 forbids them. ``` String json = "{'a':1,'a':2}"; Map map = gson.fromJson(json, mapType); 1.7: map == {a=2} 2.0: JsonSyntaxException thrown ``` * Gson 1.7 won’t serialize subclass fields in collection elements. 2.0 adds this extra information. ``` List points = new ArrayList(); points.add(new Point3d(1, 2, 3)); String json = gson.toJson(points, new TypeToken>() {}.getType()); 1.7: json == "[{'x':1,'y':2}]" 2.0: json == "[{'x':1,'y':2,'z':3}]" ``` * Gson 1.7 binds single-element arrays as their contents. 2.0 doesn’t. ``` Integer i = gson.fromJson("[42]", Integer.class); 1.7: i == 42 2.0: JsonSyntaxException thrown ``` #### Other changes to be aware of * Gson 2.0 doesn’t support type adapters for primitive types. * Gson 1.7 uses arbitrary precision for primitive type conversion (so -122.08e-2132 != 0). Gson 2.0 uses double precision (so -122.08e-2132 == 0). * Gson 1.7 sets subclass fields when an InstanceCreator returns a subclass when the value is a field of another object. Gson 2.0 sets fields of the requested type only. * Gson 1.7 versioning never skips the top-level object. Gson 2.0 versioning applies to all objects. * Gson 1.7 truncates oversized large integers. Gson 2.0 fails on them. * Gson 2.0 permits integers to have .0 fractions like "1.0". * Gson 1.7 throws IllegalStateException on circular references. Gson 2.0 lets the runtime throw a StackOverflowError. ## Version 1.7.2 _2011-09-30_ (Unplanned release) * Fixed a threading issue in FieldAttributes (Issue 354) ## Version 1.7.1 _2011-04-13_ (Unplanned release) * Fixed Gson jars in Maven Central repository * Removed assembly-descriptor.xml and maven pom.xml/pom.properties files from Gson binary jar. This also ensures that jarjar can be run correctly on Gson. ## Version 1.7 _2011-04-12_ (Targeted: Jan 2011) * No need to define no-args constructors for classes serialized with Gson * Ability to register a hierarchical type adapter * Support for serialization and deserialization of maps with complex keys * Serialization and deserialization specific exclusion strategies * Allow concrete data structure fields without type adapters * Fixes "type" management (i.e. Wildcards, etc.) * Major performance enhancements by reducing the need for Java reflection See detailed announcement at this thread in the Gson Google Group. ## Version 1.6 _2010-11-24_ (Targeted: Oct, 2010) * New stream parser APIs * New parser that improves parsing performance significantly ## Version 1.5 _2010-08-19_ (Target Date: Aug 18, 2010) * Added `UPPER_CAMEL_CASE_WITH_SPACES` naming policy * Added SQL date and time support * A number of performance improvements: Using caching of field annotations for speeding up reflection, replacing recursive calls in the parser with a for loop. ## Version 1.4 BETA _2009_10_09_ * JsonStreamParser: A streaming parser API class to deserialize multiple JSON objects on a stream (such as a pipelined HTTP response) * Raised the deserialization limit for byte and object arrays and collection to over 11MB from 80KB. See issue 96. * While serializing, Gson now uses the actual type of a field. This allows serialization of base-class references holding sub-classes to the JSON for the sub-class. It also allows serialization of raw collections. See Issue 155, 156. * Added a `Gson.toJsonTree()` method that serializes a Java object to a tree of JsonElements. See issue 110. * Added a `Gson.fromJson(JsonElement)` method that deserializes from a Json parse tree. * Updated `Expose` annotation to contain parameters serialize and deserialize to control whether a field gets serialized or deserialized. See issue 146. * Added a new naming policy `LOWER_CASE_WITH_DASHES` * Default date type adapter is now thread-safe. See Issue 162. * `JsonElement.toString()` now outputs valid JSON after escaping characters properly. See issue 154. * `JsonPrimitive.equals()` now returns true for two numbers if their values are equal. All integral types (long, int, short, byte, BigDecimal, Long, Integer, Short, Byte) are treated equivalent for comparison. Similarly, floating point types (double, float, BigDecimal, Double, Float) are treated equivalent as well. See issue 147. * Fixed bugs in pretty printing. See issue 153. * If a field causes circular reference error, Gson lists the field name instead of the object value. See issue 118. * Gson now serializes a list with null elements correctly. See issue 117. * Fixed issue 121, 123, 126. * Support user defined exclusion strategies (Feature Request 138). ## Version 1.3 _2009-04-01_ * Fix security token to remove the `` element. * Changed JsonParser.parse method to be non-static * Throw JsonParseExceptions instead of ClassCastExceptions and UnsupportedOperationExceptions ## Version 1.3 beta3 _2009-03-17_ * Supported custom mapping of field names by making `FieldNamingStrategy` public and allowing `FieldNamingStrategy` to be set in GsonBuilder. See issue 104. * Added a new GsonBuilder setting `generateNonExecutableJson()` that prefixes the generated JSON with some text to make the output non-executable Javascript. Gson now recognizes this text from input while deserializing and filters it out. This feature is meant to prevent script sourcing attacks. See Issue 42. * Supported deserialization of sets with elements that do not implement Comparable. See Issue 100 * Supported deserialization of floating point numbers without a sign after E. See Issue 94 ## Version 1.3 beta2 _2009-02-05_ * Added a new Parser API. See issue 65 * Supported deserialization of java.util.Properties. See Issue 87 * Fixed the pretty printing of maps. See Issue 93 * Supported automatic conversion of strings into numeric and boolean types if possible. See Issue 89 * Supported deserialization of longs into strings. See Issue 82 ## Version 1.3 beta1 _2009_01_ (Target Date Friday, Dec 15, 2008) * Made JSON parser lenient by allowing unquoted member names while parsing. See Issue 41 * Better precision handling for floating points. See Issue 71, 72 * Support for deserialization of special double values: NaN, infinity and negative infinity. See Issue 81 * Backward compatibility issue found with serialization of `Collection` type. See Issue 73 and 83. * Able to serialize null keys and/or values within a Map. See Issue 77 * Deserializing non-String value keys for Maps. See Issue 85. * Support for clashing field name. See Issue 76. * Removed the need to invoke instance creator if a deserializer is registered. See issues 37 and 69. * Added default support for java.util.UUID. See Issue 79 * Changed `Gson.toJson()` methods to use `Appendable` instead of `Writer`. Issue 52. This requires that clients recompile their source code that uses Gson. ## Version 1.2.3 _2008-11-15_ (Target Date Friday, Oct 31, 2008) * Added support to serialize raw maps. See issue 45 * Made Gson thread-safe by fixing Issue 63 * Fixed Issue 68 to allow default type adapters for primitive types to be replaced by custom type adapters. * Relaxed the JSON parser to accept escaped slash (\/) as a valid character in the string. See Issue 66 ## Version 1.2.2 _2008-10-14_ (Target Date: None, Unplanned) * This version was released to fix Issue 58 which caused a regression bug in version 1.2.1. It includes the contents from the release 1.2.1 ## Version 1.2.1 _2008-10-13_ (Target Date Friday, Oct 7, 2008) **Note:** This release was abandoned since it caused a regression (Issue 58) bug. * Includes updated parser for JSON that supports much larger strings. For example, Gson 1.2 failed at parsing a 100k string, Gson 1.2.1 has successfully parsed strings of size 15-20MB. The parser also is faster and consumes less memory since it uses a token match instead of a recursion-based Grammar production match. See Issue 47. * Gson now supports field names with single quotes ' in addition to double quotes ". See Issue 55. * Includes bug fixes for issue 46, 49, 51, 53, 54, and 56. ## Version 1.2 _2008-08-29_ (Target Date Tuesday Aug 26, 2008) * Includes support for feature requests 21, 24, 29 * Includes bug fixes for Issue 22, Issue 23, Issue 25, Issue 26, Issue 32 , Issue 34, Issue 35, Issue 36, Issue 37, Issue 38, Issue 39 * Performance enhancements (see r137) * Documentation updates ## Version 1.1.1 _2008-07-18_ (Target Date Friday, Aug 1, 2008) * Includes fixes for Issue 19, Partial fix for Issue 20 ## Version 1.1 _2008-07-01_ (Target Date Thursday, July 3, 2008) * Includes fixes for Issue 9, Issue 16, Issue 18 ## Version 1.0.1 _2008-06-17_ (Target Date Friday, Jun 13, 2008) * Includes fixes for Issue 15, Issue 14, Issue 3, Issue 8 * Javadoc improvements gson-gson-parent-2.8.2/GsonDesignDocument.md000066400000000000000000000151141316034351600210110ustar00rootroot00000000000000# Gson Design Document This document presents issues that we faced while designing Gson. It is meant for advanced users or developers working on Gson. If you are interested in learning how to use Gson, see its user guide. **Navigating the Json tree or the target Type Tree while deserializing** When you are deserializing a Json string into an object of desired type, you can either navigate the tree of the input, or the type tree of the desired type. Gson uses the latter approach of navigating the type of the target object. This keeps you in tight control of instantiating only the type of objects that you are expecting (essentially validating the input against the expected "schema"). By doing this, you also ignore any extra fields that the Json input has but were not expected. As part of Gson, we wrote a general purpose ObjectNavigator that can take any object and navigate through its fields calling a visitor of your choice. **Supporting richer serialization semantics than deserialization semantics** Gson supports serialization of arbitrary collections, but can only deserialize genericized collections. this means that Gson can, in some cases, fail to deserialize Json that it wrote. This is primarily a limitation of the Java type system since when you encounter a Json array of arbitrary types there is no way to detect the types of individual elements. We could have chosen to restrict the serialization to support only generic collections, but chose not to.This is because often the user of the library are concerned with either serialization or deserialization, but not both. In such cases, there is no need to artificially restrict the serialization capabilities. **Supporting serialization and deserialization of classes that are not under your control and hence can not be modified** Some Json libraries use annotations on fields or methods to indicate which fields should be used for Json serialization. That approach essentially precludes the use of classes from JDK or third-party libraries. We solved this problem by defining the notion of Custom serializers and deserializers. This approach is not new, and was used by the JAX-RPC technology to solve essentially the same problem. **Using Checked vs Unchecked exceptions to indicate a parsing error** We chose to use unchecked exceptions to indicate a parsing failure. This is primarily done because usually the client can not recover from bad input, and hence forcing them to catch a checked exception results in sloppy code in the catch() block. **Creating class instances for deserialization** Gson needs to create a dummy class instance before it can deserialize Json data into its fields. We could have used Guice to get such an instance, but that would have resulted in a dependency on Guice. Moreover, it probably would have done the wrong thing since Guice is expected to return a valid instance, whereas we need to create a dummy one. Worse, Gson would overwrite the fields of that instance with the incoming data there by modifying the instance for all subsequent Guice injections. This is clearly not a desired behavior. Hence, we create class instances by invoking the parameterless constructor. We also handle the primitive types, enums, collections, sets, maps and trees as a special case. To solve the problem of supporting unmodifiable types, we use custom instance creators. So, if you want to use a library types that does not define a default constructor (for example, Money class), then you can register an instance creator that returns a dummy instance when asked. **Using fields vs getters to indicate Json elements** Some Json libraries use the getters of a type to deduce the Json elements. We chose to use all fields (up the inheritance hierarchy) that are not transient, static, or synthetic. We did this because not all classes are written with suitably named getters. Moreover, getXXX or isXXX might be semantic rather than indicating properties. However, there are good arguments to support properties as well. We intend to enhance Gson in a latter version to support properties as an alternate mapping for indicating Json fields. For now, Gson is fields-based. **Why are most classes in Gson marked as final?** While Gson provides a fairly extensible architecture by providing pluggable serializers and deserializers, Gson classes were not specifically designed to be extensible. Providing non-final classes would have allowed a user to legitimately extend Gson classes, and then expect that behavior to work in all subsequent revisions. We chose to limit such use-cases by marking classes as final, and waiting until a good use-case emerges to allow extensibility. Marking a class final also has a minor benefit of providing additional optimization opportunities to Java compiler and virtual machine. **Why are inner interfaces and classes used heavily in Gson?** Gson uses inner classes substantially. Many of the public interfaces are inner interfaces too (see JsonSerializer.Context or JsonDeserializer.Context as an example). These are primarily done as a matter of style. For example, we could have moved JsonSerializer.Context to be a top-level class JsonSerializerContext, but chose not to do so. However, if you can give us good reasons to rename it alternately, we are open to changing this philosophy. **Why do you provide two ways of constructing Gson?** Gson can be constructed in two ways: by invoking new Gson() or by using a GsonBuilder. We chose to provide a simple no-args constructor to handle simple use-cases for Gson where you want to use default options, and quickly want to get going with writing code. For all other situations, where you need to configure Gson with options such as formatters, version controls etc, we use a builder pattern. The builder pattern allows a user to specify multiple optional settings for what essentially become constructor parameters for Gson. **Comparing Gson with Alternate Approaches** Note that these comparisons were done while developing Gson so these date back to mid to late 2007. __Comparing Gson with org.json library__ org.json is a much lower-level library that can be used to write a toJson() method in a class. If you can not use Gson directly (may be because of platform restrictions regarding reflection), you could use org.json to hand-code a toJson method in each object. __Comparing Gson with org.json.simple library__ org.json.simple library is very similar to org.json library and hence fairly low level. The key issue with this library is that it does not handle exceptions very well. In some cases it appeared to just eat the exception while in other cases it throws an "Error" rather than an exception. gson-gson-parent-2.8.2/LICENSE000066400000000000000000000261361316034351600157430ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. gson-gson-parent-2.8.2/README.md000066400000000000000000000065111316034351600162100ustar00rootroot00000000000000# google-gson [![Build Status](https://travis-ci.org/google/gson.svg?branch=master)](https://travis-ci.org/google/gson) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.google.code.gson/gson/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.google.code.gson/gson) [![Javadoc](https://javadoc-emblem.rhcloud.com/doc/com.google.code.gson/gson/badge.svg)](http://www.javadoc.io/doc/com.google.code.gson/gson) Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of. There are a few open-source projects that can convert Java objects to JSON. However, most of them require that you place Java annotations in your classes; something that you can not do if you do not have access to the source-code. Most also do not fully support the use of Java Generics. Gson considers both of these as very important design goals. ### Gson Goals * Provide simple `toJson()` and `fromJson()` methods to convert Java objects to JSON and vice-versa * Allow pre-existing unmodifiable objects to be converted to and from JSON * Extensive support of Java Generics * Allow custom representations for objects * Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types) ### Gson Download and Maven * [Gson Download](https://maven-badges.herokuapp.com/maven-central/com.google.code.gson/gson) downloads at Maven Central * For Maven check "Dependency Information" tab, on the left side. ### Gson Documentation * Gson [API](http://www.javadoc.io/doc/com.google.code.gson/gson): Javadocs for the current Gson release * Gson [user guide](https://github.com/google/gson/blob/master/UserGuide.md): This guide contains examples on how to use Gson in your code. * Gson [Roadmap](https://github.com/google/gson/blob/master/CHANGELOG.md): Details of changes in the recent versions * Gson [design document](https://github.com/google/gson/blob/master/GsonDesignDocument.md): This document discusses issues we faced while designing Gson. It also include a comparison of Gson with other Java libraries that can be used for Json conversion Please use the [google-gson Google group](http://groups.google.com/group/google-gson) to discuss Gson, or to post questions. ### Gson-related Content Created by Third Parties * [Gson Tutorial](http://www.studytrails.com/java/json/java-google-json-introduction.jsp) by `StudyTrails` * [Gson Tutorial Series](https://futurestud.io/tutorials/gson-getting-started-with-java-json-serialization-deserialization) by `Future Studio` ### License Gson is released under the [Apache 2.0 license](LICENSE). ``` Copyright 2008 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ``` gson-gson-parent-2.8.2/ReleaseProcess.md000066400000000000000000000124431316034351600201730ustar00rootroot00000000000000#Gson Release Process The following is a step-by-step procedure for releasing a new version of Google-Gson. 1. Go through all open bugs and identify which will be fixed in this release. Mark all others with an appropriate release tag. Identify duplicates, and close the bugs that will never be fixed. Fix all bugs for the release, and mark them fixed. 1. (obsolete step) Edit [`pom.xml`](pom.xml) and update the versions listed for Export-Package to the target version. Also add any new Java packages that have been introduced in Gson. 1. Ensure all changelists are code-reviewed and have +1 1. (obsolete step) Ensure that your `~/.m2/settings.xml` is configured properly (see steps below) 1. `cd gson` to the parent directory; ensure there are no open files and all changes are committed. 1. Run `mvn release:clean` 1. Do a dry run: `mvn release:prepare -DdryRun=true` 1. Start the release: `mvn release:prepare` * Answer questions: usually the defaults are fine. * This will do a full build, change version from `-SNAPSHOT` to the released version, commit and create the tags. It will then change the version to `-SNAPSHOT` for the next release. 1. Ensure you have defined `sonatype-nexus-staging` in your Maven `settings.xml` and run: ```bash mvn -s /home//.m2/settings.xml release:perform ``` 1. [Log in to Nexus repository manager](https://oss.sonatype.org/index.html#welcome) at Sonatype and close the staging repository for Gson. If you run into an error regarding missing signatures, you need to manually upload the artifacts using `mvn gpg:sign-and-deploy-file` for Gson binary, source and Javadoc jars. ```bash cp -r ~/.m2/repository/com/google/code/gson/gson/1.7.2 /tmp cd /tmp/1.7.2 mvn gpg:sign-and-deploy-file \ -Durl=https://oss.sonatype.org/service/local/staging/deploy/maven2/ \ -DrepositoryId=sonatype-nexus-staging \ -DpomFile=gson-1.7.2.pom \ -Dfile=gson-1.7.2-javadoc.jar \ -Dclassifier=javadoc mvn gpg:sign-and-deploy-file \ -Durl=https://oss.sonatype.org/service/local/staging/deploy/maven2/ \ -DrepositoryId=sonatype-nexus-staging \ -DpomFile=gson-1.7.2.pom \ -Dfile=gson-1.7.2-sources.jar \ -Dclassifier=sources mvn gpg:sign-and-deploy-file \ -Durl=https://oss.sonatype.org/service/local/staging/deploy/maven2/ \ -DrepositoryId=sonatype-nexus-staging \ -DpomFile=gson-1.7.2.pom \ -Dfile=gson-1.7.2.jar ``` 1. Close the Gson repository. Download and sanity check all downloads. Do not skip this step! Once you release the staging repository, there is no going back. It will get synced with Maven central and you will not be able to update or delete anything. Your only recourse will be to release a new version of Gson and hope that no one uses the old one. 1. Release the staging repository for Gson. Gson will now get synced to Maven central with-in the next hour. For issues consult [Sonatype Guide](https://docs.sonatype.org/display/Repository/Sonatype+OSS+Maven+Repository+Usage+Guide#SonatypeOSSMavenRepositoryUsageGuide-8.ReleaseIt). 1. Update the version in the [Using Gson with Maven2 page](https://github.com/google/gson/blob/master/UserGuide.md#TOC-Gson-With-Maven) 1. Update [Gson Changelog](https://github.com/google/gson/blob/master/CHANGELOG.md). Also, look at all bugs that were fixed and add a few lines describing what changed in the release. 1. Create a post on the [Gson Discussion Forum](http://groups.google.com/group/google-gson) 1. Update the release version in [Wikipedia](http://en.wikipedia.org/wiki/GSON) and update the current "stable" release. ## Configuring a machine for deployment to Sonatype Repository This section was borrowed heavily from [Doclava release process](http://code.google.com/p/doclava/wiki/ProcessRelease). 1. Install/Configure GPG following this [guide](http://www.sonatype.com/people/2010/01/how-to-generate-pgp-signatures-with-maven/). 2. [Create encrypted passwords](http://maven.apache.org/guides/mini/guide-encryption.html). 3. Create `~/.m2/settings.xml` similar to as described in [Doclava release process](https://code.google.com/p/doclava/wiki/ProcessRelease). 4. Now for deploying a snapshot repository, use `mvn deploy`. ## Getting Maven Publishing Privileges Based on [Gson group thread](https://groups.google.com/d/topic/google-gson/DHWJHVFpIBg/discussion): 1. [Sign up for a Sonatype account](https://docs.sonatype.org/display/Repository/Sonatype+OSS+Maven+Repository+Usage+Guide) following instructions under (2) on that page 2. Ask one of the existing members of the repository to create a JIRA ticket (Step 3 of above document) to add you to the publisher list. ## Running Benchmarks or Tests on Android * Download vogar * Put `adb` on your `$PATH` and run: ```bash vogar --benchmark --classpath gson.jar path/to/Benchmark.java ``` For example, here is how to run the [CollectionsDeserializationBenchmark](gson/src/main/java/com/google/gson/metrics/CollectionsDeserializationBenchmark.java): ```bash export ANDROID_HOME=~/apps/android-sdk-mac_x86 export PATH=$PATH:$ANDROID_HOME/platform-tools/:$ANDROID_HOME/android-sdk-mac_x86/tools/ $VOGAR_HOME/bin/vogar \ --benchmark \ --sourcepath ../gson/src/main/java/ \ src/main/java/com/google/gson/metrics/CollectionsDeserializationBenchmark.java \ -- \ --vm "app_process -Xgc:noconcurrent,app_process" ``` gson-gson-parent-2.8.2/UserGuide.md000066400000000000000000000732701316034351600171550ustar00rootroot00000000000000# Gson User Guide 1. [Overview](#TOC-Overview) 2. [Goals for Gson](#TOC-Goals-for-Gson) 3. [Gson Performance and Scalability](#TOC-Gson-Performance-and-Scalability) 4. [Gson Users](#TOC-Gson-Users) 5. [Using Gson](#TOC-Using-Gson) * [Using Gson with Maven](#TOC-Gson-With-Maven) * [Primitives Examples](#TOC-Primitives-Examples) * [Object Examples](#TOC-Object-Examples) * [Finer Points with Objects](#TOC-Finer-Points-with-Objects) * [Nested Classes (including Inner Classes)](#TOC-Nested-Classes-including-Inner-Classes-) * [Array Examples](#TOC-Array-Examples) * [Collections Examples](#TOC-Collections-Examples) * [Collections Limitations](#TOC-Collections-Limitations) * [Serializing and Deserializing Generic Types](#TOC-Serializing-and-Deserializing-Generic-Types) * [Serializing and Deserializing Collection with Objects of Arbitrary Types](#TOC-Serializing-and-Deserializing-Collection-with-Objects-of-Arbitrary-Types) * [Built-in Serializers and Deserializers](#TOC-Built-in-Serializers-and-Deserializers) * [Custom Serialization and Deserialization](#TOC-Custom-Serialization-and-Deserialization) * [Writing a Serializer](#TOC-Writing-a-Serializer) * [Writing a Deserializer](#TOC-Writing-a-Deserializer) * [Writing an Instance Creator](#TOC-Writing-an-Instance-Creator) * [InstanceCreator for a Parameterized Type](#TOC-InstanceCreator-for-a-Parameterized-Type) * [Compact Vs. Pretty Printing for JSON Output Format](#TOC-Compact-Vs.-Pretty-Printing-for-JSON-Output-Format) * [Null Object Support](#TOC-Null-Object-Support) * [Versioning Support](#TOC-Versioning-Support) * [Excluding Fields From Serialization and Deserialization](#TOC-Excluding-Fields-From-Serialization-and-Deserialization) * [Java Modifier Exclusion](#TOC-Java-Modifier-Exclusion) * [Gson's `@Expose`](#TOC-Gson-s-Expose) * [User Defined Exclusion Strategies](#TOC-User-Defined-Exclusion-Strategies) * [JSON Field Naming Support](#TOC-JSON-Field-Naming-Support) * [Sharing State Across Custom Serializers and Deserializers](#TOC-Sharing-State-Across-Custom-Serializers-and-Deserializers) * [Streaming](#TOC-Streaming) 6. [Issues in Designing Gson](#TOC-Issues-in-Designing-Gson) 7. [Future Enhancements to Gson](#TOC-Future-Enhancements-to-Gson) ## Overview Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source code of. ## Goals for Gson * Provide easy to use mechanisms like `toString()` and constructor (factory method) to convert Java to JSON and vice-versa * Allow pre-existing unmodifiable objects to be converted to and from JSON * Allow custom representations for objects * Support arbitrarily complex objects * Generate compact and readable JSON output ## Gson Performance and Scalability Here are some metrics that we obtained on a desktop (dual opteron, 8GB RAM, 64-bit Ubuntu) running lots of other things along-with the tests. You can rerun these tests by using the class [`PerformanceTest`](gson/src/test/java/com/google/gson/metrics/PerformanceTest.java). * Strings: Deserialized strings of over 25MB without any problems (see `disabled_testStringDeserializationPerformance` method in `PerformanceTest`) * Large collections: * Serialized a collection of 1.4 million objects (see `disabled_testLargeCollectionSerialization` method in `PerformanceTest`) * Deserialized a collection of 87,000 objects (see `disabled_testLargeCollectionDeserialization` in `PerformanceTest`) * Gson 1.4 raised the deserialization limit for byte arrays and collection to over 11MB from 80KB. Note: Delete the `disabled_` prefix to run these tests. We use this prefix to prevent running these tests every time we run JUnit tests. ## Gson Users Gson was originally created for use inside Google where it is currently used in a number of projects. It is now used by a number of public projects and companies. ## Using Gson The primary class to use is [`Gson`](gson/src/main/java/com/google/gson/Gson.java) which you can just create by calling `new Gson()`. There is also a class [`GsonBuilder`](gson/src/main/java/com/google/gson/GsonBuilder.java) available that can be used to create a Gson instance with various settings like version control and so on. The Gson instance does not maintain any state while invoking Json operations. So, you are free to reuse the same object for multiple Json serialization and deserialization operations. ## Using Gson with Maven To use Gson with Maven2/3, you can use the Gson version available in Maven Central by adding the following dependency: ```xml com.google.code.gson gson 2.8.0 compile ``` That is it, now your maven project is Gson enabled. ### Primitives Examples ```java // Serialization Gson gson = new Gson(); gson.toJson(1); // ==> 1 gson.toJson("abcd"); // ==> "abcd" gson.toJson(new Long(10)); // ==> 10 int[] values = { 1 }; gson.toJson(values); // ==> [1] // Deserialization int one = gson.fromJson("1", int.class); Integer one = gson.fromJson("1", Integer.class); Long one = gson.fromJson("1", Long.class); Boolean false = gson.fromJson("false", Boolean.class); String str = gson.fromJson("\"abc\"", String.class); String[] anotherStr = gson.fromJson("[\"abc\"]", String[].class); ``` ### Object Examples ```java class BagOfPrimitives { private int value1 = 1; private String value2 = "abc"; private transient int value3 = 3; BagOfPrimitives() { // no-args constructor } } // Serialization BagOfPrimitives obj = new BagOfPrimitives(); Gson gson = new Gson(); String json = gson.toJson(obj); // ==> json is {"value1":1,"value2":"abc"} ``` Note that you can not serialize objects with circular references since that will result in infinite recursion. ```java // Deserialization BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class); // ==> obj2 is just like obj ``` #### **Finer Points with Objects** * It is perfectly fine (and recommended) to use private fields * There is no need to use any annotations to indicate a field is to be included for serialization and deserialization. All fields in the current class (and from all super classes) are included by default. * If a field is marked transient, (by default) it is ignored and not included in the JSON serialization or deserialization. * This implementation handles nulls correctly * While serializing, a null field is skipped from the output * While deserializing, a missing entry in JSON results in setting the corresponding field in the object to null * If a field is _synthetic_, it is ignored and not included in JSON serialization or deserialization * Fields corresponding to the outer classes in inner classes, anonymous classes, and local classes are ignored and not included in serialization or deserialization ### Nested Classes (including Inner Classes) Gson can serialize static nested classes quite easily. Gson can also deserialize static nested classes. However, Gson can **not** automatically deserialize the **pure inner classes since their no-args constructor also need a reference to the containing Object** which is not available at the time of deserialization. You can address this problem by either making the inner class static or by providing a custom InstanceCreator for it. Here is an example: ```java public class A { public String a; class B { public String b; public B() { // No args constructor for B } } } ``` **NOTE**: The above class B can not (by default) be serialized with Gson. Gson can not deserialize `{"b":"abc"}` into an instance of B since the class B is an inner class. If it was defined as static class B then Gson would have been able to deserialize the string. Another solution is to write a custom instance creator for B. ```java public class InstanceCreatorForB implements InstanceCreator { private final A a; public InstanceCreatorForB(A a) { this.a = a; } public A.B createInstance(Type type) { return a.new B(); } } ``` The above is possible, but not recommended. ### Array Examples ```java Gson gson = new Gson(); int[] ints = {1, 2, 3, 4, 5}; String[] strings = {"abc", "def", "ghi"}; // Serialization gson.toJson(ints); // ==> [1,2,3,4,5] gson.toJson(strings); // ==> ["abc", "def", "ghi"] // Deserialization int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class); // ==> ints2 will be same as ints ``` We also support multi-dimensional arrays, with arbitrarily complex element types. ### Collections Examples ```java Gson gson = new Gson(); Collection ints = Lists.immutableList(1,2,3,4,5); // Serialization String json = gson.toJson(ints); // ==> json is [1,2,3,4,5] // Deserialization Type collectionType = new TypeToken>(){}.getType(); Collection ints2 = gson.fromJson(json, collectionType); // ==> ints2 is same as ints ``` Fairly hideous: note how we define the type of collection. Unfortunately, there is no way to get around this in Java. #### Collections Limitations Gson can serialize collection of arbitrary objects but can not deserialize from it, because there is no way for the user to indicate the type of the resulting object. Instead, while deserializing, the Collection must be of a specific, generic type. This makes sense, and is rarely a problem when following good Java coding practices. ### Serializing and Deserializing Generic Types When you call `toJson(obj)`, Gson calls `obj.getClass()` to get information on the fields to serialize. Similarly, you can typically pass `MyClass.class` object in the `fromJson(json, MyClass.class)` method. This works fine if the object is a non-generic type. However, if the object is of a generic type, then the Generic type information is lost because of Java Type Erasure. Here is an example illustrating the point: ```java class Foo { T value; } Gson gson = new Gson(); Foo foo = new Foo(); gson.toJson(foo); // May not serialize foo.value correctly gson.fromJson(json, foo.getClass()); // Fails to deserialize foo.value as Bar ``` The above code fails to interpret value as type Bar because Gson invokes `list.getClass()` to get its class information, but this method returns a raw class, `Foo.class`. This means that Gson has no way of knowing that this is an object of type `Foo`, and not just plain `Foo`. You can solve this problem by specifying the correct parameterized type for your generic type. You can do this by using the [`TypeToken`](http://google.github.io/gson/apidocs/com/google/gson/reflect/TypeToken.html) class. ```java Type fooType = new TypeToken>() {}.getType(); gson.toJson(foo, fooType); gson.fromJson(json, fooType); ``` The idiom used to get `fooType` actually defines an anonymous local inner class containing a method `getType()` that returns the fully parameterized type. ### Serializing and Deserializing Collection with Objects of Arbitrary Types Sometimes you are dealing with JSON array that contains mixed types. For example: `['hello',5,{name:'GREETINGS',source:'guest'}]` The equivalent `Collection` containing this is: ```java Collection collection = new ArrayList(); collection.add("hello"); collection.add(5); collection.add(new Event("GREETINGS", "guest")); ``` where the `Event` class is defined as: ```java class Event { private String name; private String source; private Event(String name, String source) { this.name = name; this.source = source; } } ``` You can serialize the collection with Gson without doing anything specific: `toJson(collection)` would write out the desired output. However, deserialization with `fromJson(json, Collection.class)` will not work since Gson has no way of knowing how to map the input to the types. Gson requires that you provide a genericised version of collection type in `fromJson()`. So, you have three options: 1. Use Gson's parser API (low-level streaming parser or the DOM parser JsonParser) to parse the array elements and then use `Gson.fromJson()` on each of the array elements.This is the preferred approach. [Here is an example](extras/src/main/java/com/google/gson/extras/examples/rawcollections/RawCollectionsExample.java) that demonstrates how to do this. 2. Register a type adapter for `Collection.class` that looks at each of the array members and maps them to appropriate objects. The disadvantage of this approach is that it will screw up deserialization of other collection types in Gson. 3. Register a type adapter for `MyCollectionMemberType` and use `fromJson()` with `Collection`. This approach is practical only if the array appears as a top-level element or if you can change the field type holding the collection to be of type `Collection`. ### Built-in Serializers and Deserializers Gson has built-in serializers and deserializers for commonly used classes whose default representation may be inappropriate. Here is a list of such classes: 1. `java.net.URL` to match it with strings like `"https://github.com/google/gson/"` 2. `java.net.URI` to match it with strings like `"/google/gson/"` You can also find source code for some commonly used classes such as JodaTime at [this page](https://sites.google.com/site/gson/gson-type-adapters-for-common-classes-1). ### Custom Serialization and Deserialization Sometimes default representation is not what you want. This is often the case when dealing with library classes (DateTime, etc). Gson allows you to register your own custom serializers and deserializers. This is done by defining two parts: * Json Serializers: Need to define custom serialization for an object * Json Deserializers: Needed to define custom deserialization for a type * Instance Creators: Not needed if no-args constructor is available or a deserializer is registered ```java GsonBuilder gson = new GsonBuilder(); gson.registerTypeAdapter(MyType2.class, new MyTypeAdapter()); gson.registerTypeAdapter(MyType.class, new MySerializer()); gson.registerTypeAdapter(MyType.class, new MyDeserializer()); gson.registerTypeAdapter(MyType.class, new MyInstanceCreator()); ``` `registerTypeAdapter` call checks if the type adapter implements more than one of these interfaces and register it for all of them. #### Writing a Serializer Here is an example of how to write a custom serializer for JodaTime `DateTime` class. ```java private class DateTimeSerializer implements JsonSerializer { public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.toString()); } } ``` Gson calls `serialize()` when it runs into a `DateTime` object during serialization. #### Writing a Deserializer Here is an example of how to write a custom deserializer for JodaTime DateTime class. ```java private class DateTimeDeserializer implements JsonDeserializer { public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return new DateTime(json.getAsJsonPrimitive().getAsString()); } } ``` Gson calls `deserialize` when it needs to deserialize a JSON string fragment into a DateTime object **Finer points with Serializers and Deserializers** Often you want to register a single handler for all generic types corresponding to a raw type * For example, suppose you have an `Id` class for id representation/translation (i.e. an internal vs. external representation). * `Id` type that has same serialization for all generic types * Essentially write out the id value * Deserialization is very similar but not exactly the same * Need to call `new Id(Class, String)` which returns an instance of `Id` Gson supports registering a single handler for this. You can also register a specific handler for a specific generic type (say `Id` needed special handling). The `Type` parameter for the `toJson()` and `fromJson()` contains the generic type information to help you write a single handler for all generic types corresponding to the same raw type. ### Writing an Instance Creator While deserializing an Object, Gson needs to create a default instance of the class. Well-behaved classes that are meant for serialization and deserialization should have a no-argument constructor. * Doesn't matter whether public or private Typically, Instance Creators are needed when you are dealing with a library class that does NOT define a no-argument constructor **Instance Creator Example** ```java private class MoneyInstanceCreator implements InstanceCreator { public Money createInstance(Type type) { return new Money("1000000", CurrencyCode.USD); } } ``` Type could be of a corresponding generic type * Very useful to invoke constructors which need specific generic type information * For example, if the `Id` class stores the class for which the Id is being created #### InstanceCreator for a Parameterized Type Sometimes the type that you are trying to instantiate is a parameterized type. Generally, this is not a problem since the actual instance is of raw type. Here is an example: ```java class MyList extends ArrayList { } class MyListInstanceCreator implements InstanceCreator> { @SuppressWarnings("unchecked") public MyList createInstance(Type type) { // No need to use a parameterized list since the actual instance will have the raw type anyway. return new MyList(); } } ``` However, sometimes you do need to create instance based on the actual parameterized type. In this case, you can use the type parameter being passed to the `createInstance` method. Here is an example: ```java public class Id { private final Class classOfId; private final long value; public Id(Class classOfId, long value) { this.classOfId = classOfId; this.value = value; } } class IdInstanceCreator implements InstanceCreator> { public Id createInstance(Type type) { Type[] typeParameters = ((ParameterizedType)type).getActualTypeArguments(); Type idType = typeParameters[0]; // Id has only one parameterized type T return Id.get((Class)idType, 0L); } } ``` In the above example, an instance of the Id class can not be created without actually passing in the actual type for the parameterized type. We solve this problem by using the passed method parameter, `type`. The `type` object in this case is the Java parameterized type representation of `Id` where the actual instance should be bound to `Id`. Since `Id` class has just one parameterized type parameter, `T`, we use the zeroth element of the type array returned by `getActualTypeArgument()` which will hold `Foo.class` in this case. ### Compact Vs. Pretty Printing for JSON Output Format The default JSON output that is provided by Gson is a compact JSON format. This means that there will not be any whitespace in the output JSON structure. Therefore, there will be no whitespace between field names and its value, object fields, and objects within arrays in the JSON output. As well, "null" fields will be ignored in the output (NOTE: null values will still be included in collections/arrays of objects). See the [Null Object Support](#TOC-Null-Object-Support) section for information on configure Gson to output all null values. If you would like to use the Pretty Print feature, you must configure your `Gson` instance using the `GsonBuilder`. The `JsonFormatter` is not exposed through our public API, so the client is unable to configure the default print settings/margins for the JSON output. For now, we only provide a default `JsonPrintFormatter` that has default line length of 80 character, 2 character indentation, and 4 character right margin. The following is an example shows how to configure a `Gson` instance to use the default `JsonPrintFormatter` instead of the `JsonCompactFormatter`: ``` Gson gson = new GsonBuilder().setPrettyPrinting().create(); String jsonOutput = gson.toJson(someObject); ``` ### Null Object Support The default behaviour that is implemented in Gson is that `null` object fields are ignored. This allows for a more compact output format; however, the client must define a default value for these fields as the JSON format is converted back into its Java form. Here's how you would configure a `Gson` instance to output null: ```java Gson gson = new GsonBuilder().serializeNulls().create(); ``` NOTE: when serializing `null`s with Gson, it will add a `JsonNull` element to the `JsonElement` structure. Therefore, this object can be used in custom serialization/deserialization. Here's an example: ```java public class Foo { private final String s; private final int i; public Foo() { this(null, 5); } public Foo(String s, int i) { this.s = s; this.i = i; } } Gson gson = new GsonBuilder().serializeNulls().create(); Foo foo = new Foo(); String json = gson.toJson(foo); System.out.println(json); json = gson.toJson(null); System.out.println(json); ``` The output is: ``` {"s":null,"i":5} null ``` ### Versioning Support Multiple versions of the same object can be maintained by using [@Since](gson/src/main/java/com/google/gson/annotations/Since.java) annotation. This annotation can be used on Classes, Fields and, in a future release, Methods. In order to leverage this feature, you must configure your `Gson` instance to ignore any field/object that is greater than some version number. If no version is set on the `Gson` instance then it will serialize and deserialize all fields and classes regardless of the version. ```java public class VersionedClass { @Since(1.1) private final String newerField; @Since(1.0) private final String newField; private final String field; public VersionedClass() { this.newerField = "newer"; this.newField = "new"; this.field = "old"; } } VersionedClass versionedObject = new VersionedClass(); Gson gson = new GsonBuilder().setVersion(1.0).create(); String jsonOutput = gson.toJson(someObject); System.out.println(jsonOutput); System.out.println(); gson = new Gson(); jsonOutput = gson.toJson(someObject); System.out.println(jsonOutput); ``` The output is: ``` {"newField":"new","field":"old"} {"newerField":"newer","newField":"new","field":"old"} ``` ### Excluding Fields From Serialization and Deserialization Gson supports numerous mechanisms for excluding top-level classes, fields and field types. Below are pluggable mechanisms that allow field and class exclusion. If none of the below mechanisms satisfy your needs then you can always use [custom serializers and deserializers](#TOC-Custom-Serialization-and-Deserialization). #### Java Modifier Exclusion By default, if you mark a field as `transient`, it will be excluded. As well, if a field is marked as `static` then by default it will be excluded. If you want to include some transient fields then you can do the following: ```java import java.lang.reflect.Modifier; Gson gson = new GsonBuilder() .excludeFieldsWithModifiers(Modifier.STATIC) .create(); ``` NOTE: you can give any number of the `Modifier` constants to the `excludeFieldsWithModifiers` method. For example: ```java Gson gson = new GsonBuilder() .excludeFieldsWithModifiers(Modifier.STATIC, Modifier.TRANSIENT, Modifier.VOLATILE) .create(); ``` #### Gson's `@Expose` This feature provides a way where you can mark certain fields of your objects to be excluded for consideration for serialization and deserialization to JSON. To use this annotation, you must create Gson by using `new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()`. The Gson instance created will exclude all fields in a class that are not marked with `@Expose` annotation. #### User Defined Exclusion Strategies If the above mechanisms for excluding fields and class type do not work for you then you can always write your own exclusion strategy and plug it into Gson. See the [`ExclusionStrategy`](http://google.github.io/gson/apidocs/com/google/gson/ExclusionStrategy.html) JavaDoc for more information. The following example shows how to exclude fields marked with a specific `@Foo` annotation and excludes top-level types (or declared field type) of class `String`. ```java @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) public @interface Foo { // Field tag only annotation } public class SampleObjectForTest { @Foo private final int annotatedField; private final String stringField; private final long longField; private final Class clazzField; public SampleObjectForTest() { annotatedField = 5; stringField = "someDefaultValue"; longField = 1234; } } public class MyExclusionStrategy implements ExclusionStrategy { private final Class typeToSkip; private MyExclusionStrategy(Class typeToSkip) { this.typeToSkip = typeToSkip; } public boolean shouldSkipClass(Class clazz) { return (clazz == typeToSkip); } public boolean shouldSkipField(FieldAttributes f) { return f.getAnnotation(Foo.class) != null; } } public static void main(String[] args) { Gson gson = new GsonBuilder() .setExclusionStrategies(new MyExclusionStrategy(String.class)) .serializeNulls() .create(); SampleObjectForTest src = new SampleObjectForTest(); String json = gson.toJson(src); System.out.println(json); } ``` The output is: ``` {"longField":1234} ``` ### JSON Field Naming Support Gson supports some pre-defined field naming policies to convert the standard Java field names (i.e., camel cased names starting with lower case --- `sampleFieldNameInJava`) to a Json field name (i.e., `sample_field_name_in_java` or `SampleFieldNameInJava`). See the [FieldNamingPolicy](http://google.github.io/gson/apidocs/com/google/gson/FieldNamingPolicy.html) class for information on the pre-defined naming policies. It also has an annotation based strategy to allows clients to define custom names on a per field basis. Note, that the annotation based strategy has field name validation which will raise "Runtime" exceptions if an invalid field name is provided as the annotation value. The following is an example of how to use both Gson naming policy features: ```java private class SomeObject { @SerializedName("custom_naming") private final String someField; private final String someOtherField; public SomeObject(String a, String b) { this.someField = a; this.someOtherField = b; } } SomeObject someObject = new SomeObject("first", "second"); Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create(); String jsonRepresentation = gson.toJson(someObject); System.out.println(jsonRepresentation); ``` The output is: ``` {"custom_naming":"first","SomeOtherField":"second"} ``` If you have a need for custom naming policy ([see this discussion](http://groups.google.com/group/google-gson/browse_thread/thread/cb441a2d717f6892)), you can use the [@SerializedName](http://google.github.io/gson/apidocs/com/google/gson/annotations/SerializedName.html) annotation. ### Sharing State Across Custom Serializers and Deserializers Sometimes you need to share state across custom serializers/deserializers ([see this discussion](http://groups.google.com/group/google-gson/browse_thread/thread/2850010691ea09fb)). You can use the following three strategies to accomplish this: 1. Store shared state in static fields 2. Declare the serializer/deserializer as inner classes of a parent type, and use the instance fields of parent type to store shared state 3. Use Java `ThreadLocal` 1 and 2 are not thread-safe options, but 3 is. ### Streaming In addition Gson's object model and data binding, you can use Gson to read from and write to a [stream](https://sites.google.com/site/gson/streaming). You can also combine streaming and object model access to get the best of both approaches. ## Issues in Designing Gson See the [Gson design document](https://github.com/google/gson/blob/master/GsonDesignDocument.md "Gson design document") for a discussion of issues we faced while designing Gson. It also include a comparison of Gson with other Java libraries that can be used for Json conversion. ## Future Enhancements to Gson For the latest list of proposed enhancements or if you'd like to suggest new ones, see the [Issues section](https://github.com/google/gson/issues) under the project website. gson-gson-parent-2.8.2/codegen/000077500000000000000000000000001316034351600163325ustar00rootroot00000000000000gson-gson-parent-2.8.2/codegen/pom.xml000066400000000000000000000133041316034351600176500ustar00rootroot00000000000000 4.0.0 com.google.code.gson gson-codegen jar 1.0-SNAPSHOT 2008 Gson Code Gen org.sonatype.oss oss-parent 7 http://code.google.com/p/google-gson/ Google Gson grab bag of utilities, type adapters, etc. UTF-8 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt repo scm:svn:http://google-gson.googlecode.com/svn/trunk/extras scm:svn:https://google-gson.googlecode.com/svn/trunk/extras http://google-gson.codegoogle.com/svn/trunk/extras Google Code Issue Tracking http://code.google.com/p/google-gson/issues/list Google, Inc. http://www.google.com junit junit 3.8.2 test release-sign-artifacts performRelease true org.apache.maven.plugins maven-gpg-plugin 1.4 sign-artifacts verify sign package org.apache.maven.plugins maven-compiler-plugin 2.5.1 1.6 1.6 -proc:none org.apache.maven.plugins maven-jar-plugin 2.4 package jar false org.apache.maven.plugins maven-source-plugin 2.1.2 attach-sources verify jar org.apache.maven.plugins maven-javadoc-plugin 2.8.1 attach-javadocs jar http://download.oracle.com/javase/1.5.0/docs/api/ true public org.apache.maven.plugins maven-eclipse-plugin 2.9 true true ../eclipse-ws/ file:///${basedir}/../lib/gson-formatting-styles.xml org.apache.maven.plugins maven-release-plugin -DenableCiProfile=true https://google-gson.googlecode.com/svn/tags/ Inderjeet Singh Trymph Inc. Joel Leitch Google Inc. Jesse Wilson Square Inc. gson-gson-parent-2.8.2/codegen/src/000077500000000000000000000000001316034351600171215ustar00rootroot00000000000000gson-gson-parent-2.8.2/codegen/src/main/000077500000000000000000000000001316034351600200455ustar00rootroot00000000000000gson-gson-parent-2.8.2/codegen/src/main/java/000077500000000000000000000000001316034351600207665ustar00rootroot00000000000000gson-gson-parent-2.8.2/codegen/src/main/java/com/000077500000000000000000000000001316034351600215445ustar00rootroot00000000000000gson-gson-parent-2.8.2/codegen/src/main/java/com/google/000077500000000000000000000000001316034351600230205ustar00rootroot00000000000000gson-gson-parent-2.8.2/codegen/src/main/java/com/google/gson/000077500000000000000000000000001316034351600237665ustar00rootroot00000000000000gson-gson-parent-2.8.2/codegen/src/main/java/com/google/gson/codegen/000077500000000000000000000000001316034351600253725ustar00rootroot00000000000000gson-gson-parent-2.8.2/codegen/src/main/java/com/google/gson/codegen/CodeGen.java000066400000000000000000000033721316034351600275460ustar00rootroot00000000000000/* * Copyright (C) 2012 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.codegen; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; public class CodeGen { private CodeGen() { } public static PackageElement getPackage(Element type) { while (type.getKind() != ElementKind.PACKAGE) { type = type.getEnclosingElement(); } return (PackageElement) type; } /** * Returns a fully qualified class name to complement {@code type}. */ public static String adapterName(TypeElement typeElement, String suffix) { StringBuilder builder = new StringBuilder(); rawTypeToString(builder, typeElement, '$'); builder.append(suffix); return builder.toString(); } static void rawTypeToString(StringBuilder result, TypeElement type, char innerClassSeparator) { String packageName = getPackage(type).getQualifiedName().toString(); String qualifiedName = type.getQualifiedName().toString(); result.append(packageName); result.append('.'); result.append( qualifiedName.substring(packageName.length() + 1).replace('.', innerClassSeparator)); } } gson-gson-parent-2.8.2/codegen/src/main/java/com/google/gson/codegen/GeneratedTypeAdapter.java000066400000000000000000000013071316034351600322770ustar00rootroot00000000000000/* * Copyright (C) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.codegen; public @interface GeneratedTypeAdapter { Class[] value() default {}; } GeneratedTypeAdapterProcessor.java000066400000000000000000000045541316034351600341270ustar00rootroot00000000000000gson-gson-parent-2.8.2/codegen/src/main/java/com/google/gson/codegen/* * Copyright (C) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.codegen; import static java.lang.reflect.Modifier.FINAL; import java.io.IOException; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.annotation.processing.SupportedSourceVersion; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic; import javax.tools.JavaFileObject; @SupportedAnnotationTypes("com.google.gson.codegen.GeneratedTypeAdapter") @SupportedSourceVersion(SourceVersion.RELEASE_6) public final class GeneratedTypeAdapterProcessor extends AbstractProcessor { @Override public boolean process(Set types, RoundEnvironment env) { System.out.println("invoked GeneratedTypeAdapterProcessor"); try { for (Element element : env.getElementsAnnotatedWith(GeneratedTypeAdapter.class)) { writeAdapter((TypeElement) element); } } catch (IOException e) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage()); } return true; } private void writeAdapter(TypeElement type) throws IOException { String typeAdapterName = CodeGen.adapterName(type, "$TypeAdapter"); JavaFileObject sourceFile = processingEnv.getFiler() .createSourceFile(typeAdapterName, type); System.out.println("Generating type adapter: " + typeAdapterName + " in " + sourceFile.getName()); JavaWriter writer = new JavaWriter(sourceFile.openWriter()); writer.addPackage(CodeGen.getPackage(type).getQualifiedName().toString()); writer.beginType(typeAdapterName, "class", FINAL, null); writer.endType(); writer.close(); } } gson-gson-parent-2.8.2/codegen/src/main/java/com/google/gson/codegen/JavaWriter.java000066400000000000000000000265761316034351600303330ustar00rootroot00000000000000/** * Copyright (C) 2012 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.codegen; import java.io.IOException; import java.io.Writer; import java.lang.annotation.Annotation; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Emits Java source files. */ public final class JavaWriter { private static final Pattern TYPE_PATTERN = Pattern.compile("(?:[\\w$]+\\.)*([\\w$]+)"); private static final String INDENT = " "; /** Map fully qualified type names to their short names. */ private final Map importedTypes = new HashMap(); private String packagePrefix; private final List scopes = new ArrayList(); private final Writer out; /** * @param out the stream to which Java source will be written. This should be * a buffered stream. */ public JavaWriter(Writer out) { this.out = out; } /** * Emit a package declaration. */ public void addPackage(String packageName) throws IOException { if (this.packagePrefix != null) { throw new IllegalStateException(); } out.write("package "); out.write(packageName); out.write(";\n"); this.packagePrefix = packageName + "."; } /** * Equivalent to {@code addImport(type.getName())}. */ public void addImport(Class type) throws IOException { addImport(type.getName()); } /** * Emit an import for {@code type}. For the duration of the file, all * references to this class will be automatically shortened. */ public void addImport(String type) throws IOException { Matcher matcher = TYPE_PATTERN.matcher(type); if (!matcher.matches()) { throw new IllegalArgumentException(type); } if (importedTypes.put(type, matcher.group(1)) != null) { throw new IllegalArgumentException(type); } out.write("import "); out.write(type); out.write(";\n"); } /** * Emits a name like {@code java.lang.String} or {@code * java.util.List}, shorting it with imports if * possible. */ private void type(String type) throws IOException { if (this.packagePrefix == null) { throw new IllegalStateException(); } Matcher m = TYPE_PATTERN.matcher(type); int pos = 0; while (true) { boolean found = m.find(pos); // copy non-matching characters like "<" int typeStart = found ? m.start() : type.length(); out.write(type, pos, typeStart - pos); if (!found) { break; } // copy a single class name, shortening it if possible String name = m.group(0); String imported; if ((imported = importedTypes.get(name)) != null) { out.write(imported); } else if (name.startsWith(packagePrefix) && name.indexOf('.', packagePrefix.length()) == -1) { out.write(name.substring(packagePrefix.length())); } else if (name.startsWith("java.lang.")) { out.write(name.substring("java.lang.".length())); } else { out.write(name); } pos = m.end(); } } /** * Emits a type declaration. * * @param kind such as "class", "interface" or "enum". */ public void beginType(String type, String kind, int modifiers) throws IOException { beginType(type, kind, modifiers, null); } /** * Emits a type declaration. * * @param kind such as "class", "interface" or "enum". * @param extendsType the class to extend, or null for no extends clause. */ public void beginType(String type, String kind, int modifiers, String extendsType, String... implementsTypes) throws IOException { indent(); modifiers(modifiers); out.write(kind); out.write(" "); type(type); if (extendsType != null) { out.write("\n"); indent(); out.write(" extends "); type(extendsType); } if (implementsTypes.length > 0) { out.write("\n"); indent(); out.write(" implements "); for (int i = 0; i < implementsTypes.length; i++) { if (i != 0) { out.write(", "); } type(implementsTypes[i]); } } out.write(" {\n"); pushScope(Scope.TYPE_DECLARATION); } /** * Completes the current type declaration. */ public void endType() throws IOException { if (popScope() != Scope.TYPE_DECLARATION) { throw new IllegalStateException(); } indent(); out.write("}\n"); } /** * Emits a field declaration. */ public void field(String type, String name, int modifiers) throws IOException { field(type, name, modifiers, null); } public void field(String type, String name, int modifiers, String initialValue) throws IOException { indent(); modifiers(modifiers); type(type); out.write(" "); out.write(name); if (initialValue != null) { out.write(" = "); out.write(initialValue); } out.write(";\n"); } /** * Emit a method declaration. * * @param returnType the method's return type, or null for constructors. * @param parameters alternating parameter types and names. * @param name the method name, or the fully qualified class name for * constructors. */ public void beginMethod(String returnType, String name, int modifiers, String... parameters) throws IOException { indent(); modifiers(modifiers); if (returnType != null) { type(returnType); out.write(" "); out.write(name); } else { type(name); } out.write("("); for (int p = 0; p < parameters.length; ) { if (p != 0) { out.write(", "); } type(parameters[p++]); out.write(" "); type(parameters[p++]); } out.write(")"); if ((modifiers & Modifier.ABSTRACT) != 0) { out.write(";\n"); pushScope(Scope.ABSTRACT_METHOD); } else { out.write(" {\n"); pushScope(Scope.NON_ABSTRACT_METHOD); } } /** * Annotates the next element with {@code annotation}. The annotation has no * attributes. */ public void annotation(String annotation) throws IOException { indent(); out.write("@"); type(annotation); out.write("\n"); } /** * Equivalent to {@code annotation(annotationType.getName())}. */ public void annotation(Class annotationType) throws IOException { annotation(annotationType.getName()); } /** * @param pattern a code pattern like "int i = %s". Shouldn't contain a * trailing semicolon or newline character. */ public void statement(String pattern, Object... args) throws IOException { checkInMethod(); indent(); out.write(String.format(pattern, args)); out.write(";\n"); } /** * @param controlFlow the control flow construct and its code, such as * "if (foo == 5)". Shouldn't contain braces or newline characters. */ public void beginControlFlow(String controlFlow) throws IOException { checkInMethod(); indent(); out.write(controlFlow); out.write(" {\n"); pushScope(Scope.CONTROL_FLOW); } /** * @param controlFlow the control flow construct and its code, such as * "else if (foo == 10)". Shouldn't contain braces or newline characters. */ public void nextControlFlow(String controlFlow) throws IOException { if (popScope() != Scope.CONTROL_FLOW) { throw new IllegalArgumentException(); } indent(); pushScope(Scope.CONTROL_FLOW); out.write("} "); out.write(controlFlow); out.write(" {\n"); } public void endControlFlow() throws IOException { endControlFlow(null); } /** * @param controlFlow the optional control flow construct and its code, such * as "while(foo == 20)". Only used for "do/while" control flows. */ public void endControlFlow(String controlFlow) throws IOException { if (popScope() != Scope.CONTROL_FLOW) { throw new IllegalArgumentException(); } indent(); if (controlFlow != null) { out.write("} "); out.write(controlFlow); out.write(";\n"); } else { out.write("}\n"); } } /** * Completes the current method declaration. */ public void endMethod() throws IOException { Scope popped = popScope(); if (popped == Scope.NON_ABSTRACT_METHOD) { indent(); out.write("}\n"); } else if (popped != Scope.ABSTRACT_METHOD) { throw new IllegalStateException(); } } /** * Returns the string literal representing {@code data}, including wrapping * quotes. */ public static String stringLiteral(String data) { StringBuilder result = new StringBuilder(); result.append('"'); for (int i = 0; i < data.length(); i++) { char c = data.charAt(i); switch (c) { case '"': result.append("\\\""); break; case '\\': result.append("\\\\"); break; case '\t': result.append("\\\t"); break; case '\b': result.append("\\\b"); break; case '\n': result.append("\\\n"); break; case '\r': result.append("\\\r"); break; case '\f': result.append("\\\f"); break; default: result.append(c); } } result.append('"'); return result.toString(); } public void close() throws IOException { out.close(); } /** * Emit modifier names. */ private void modifiers(int modifiers) throws IOException { if ((modifiers & Modifier.PUBLIC) != 0) { out.write("public "); } if ((modifiers & Modifier.PRIVATE) != 0) { out.write("private "); } if ((modifiers & Modifier.PROTECTED) != 0) { out.write("protected "); } if ((modifiers & Modifier.STATIC) != 0) { out.write("static "); } if ((modifiers & Modifier.FINAL) != 0) { out.write("final "); } if ((modifiers & Modifier.ABSTRACT) != 0) { out.write("abstract "); } if ((modifiers & Modifier.SYNCHRONIZED) != 0) { out.write("synchronized "); } if ((modifiers & Modifier.TRANSIENT) != 0) { out.write("transient "); } if ((modifiers & Modifier.VOLATILE) != 0) { out.write("volatile "); } } private void indent() throws IOException { for (int i = 0; i < scopes.size(); i++) { out.write(INDENT); } } private void checkInMethod() { Scope scope = peekScope(); if (scope != Scope.NON_ABSTRACT_METHOD && scope != Scope.CONTROL_FLOW) { throw new IllegalArgumentException(); } } private void pushScope(Scope pushed) { scopes.add(pushed); } private Scope peekScope() { return scopes.get(scopes.size() - 1); } private Scope popScope() { return scopes.remove(scopes.size() - 1); } private enum Scope { TYPE_DECLARATION, ABSTRACT_METHOD, NON_ABSTRACT_METHOD, CONTROL_FLOW, } } gson-gson-parent-2.8.2/codegen/src/main/resources/000077500000000000000000000000001316034351600220575ustar00rootroot00000000000000gson-gson-parent-2.8.2/codegen/src/main/resources/META-INF/000077500000000000000000000000001316034351600232175ustar00rootroot00000000000000gson-gson-parent-2.8.2/codegen/src/main/resources/META-INF/services/000077500000000000000000000000001316034351600250425ustar00rootroot00000000000000javax.annotation.processing.Processor000066400000000000000000000000651316034351600343220ustar00rootroot00000000000000gson-gson-parent-2.8.2/codegen/src/main/resources/META-INF/servicescom.google.gson.codegen.GeneratedTypeAdapterProcessorgson-gson-parent-2.8.2/codegen/src/test/000077500000000000000000000000001316034351600201005ustar00rootroot00000000000000gson-gson-parent-2.8.2/codegen/src/test/java/000077500000000000000000000000001316034351600210215ustar00rootroot00000000000000gson-gson-parent-2.8.2/codegen/src/test/java/com/000077500000000000000000000000001316034351600215775ustar00rootroot00000000000000gson-gson-parent-2.8.2/codegen/src/test/java/com/google/000077500000000000000000000000001316034351600230535ustar00rootroot00000000000000gson-gson-parent-2.8.2/codegen/src/test/java/com/google/gson/000077500000000000000000000000001316034351600240215ustar00rootroot00000000000000gson-gson-parent-2.8.2/codegen/src/test/java/com/google/gson/codegen/000077500000000000000000000000001316034351600254255ustar00rootroot00000000000000gson-gson-parent-2.8.2/codegen/src/test/java/com/google/gson/codegen/functional/000077500000000000000000000000001316034351600275675ustar00rootroot00000000000000CodeGenFunctionalTest.java000066400000000000000000000015611316034351600345450ustar00rootroot00000000000000gson-gson-parent-2.8.2/codegen/src/test/java/com/google/gson/codegen/functional/* * Copyright (C) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.codegen.functional; import junit.framework.TestCase; public class CodeGenFunctionalTest extends TestCase { public void testGeneratedJson() { Order order = new Order("toy", 10); // TODO: figure out how to access the generated type adapter } } gson-gson-parent-2.8.2/codegen/src/test/java/com/google/gson/codegen/functional/Order.java000066400000000000000000000017671316034351600315200ustar00rootroot00000000000000/* * Copyright (C) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.codegen.functional; import com.google.gson.codegen.GeneratedTypeAdapter; @GeneratedTypeAdapter final class Order { private final String itemName; private final int price; public Order(String itemName, int price) { this.itemName = itemName; this.price = price; } public String getItemName() { return itemName; } public int getAmount() { return price; } } gson-gson-parent-2.8.2/examples/000077500000000000000000000000001316034351600165445ustar00rootroot00000000000000gson-gson-parent-2.8.2/examples/android-proguard-example/000077500000000000000000000000001316034351600234365ustar00rootroot00000000000000gson-gson-parent-2.8.2/examples/android-proguard-example/AndroidManifest.xml000077500000000000000000000016131316034351600272330ustar00rootroot00000000000000 gson-gson-parent-2.8.2/examples/android-proguard-example/default.properties000066400000000000000000000006061316034351600272020ustar00rootroot00000000000000# This file is automatically generated by Android Tools. # Do not modify this file -- YOUR CHANGES WILL BE ERASED! # # This file must be checked in Version Control Systems. # # To customize properties used by the Ant build system use, # "build.properties", and override values to adapt the script to your # project structure. # Project target. target=android-3 proguard.config=proguard.cfggson-gson-parent-2.8.2/examples/android-proguard-example/proguard.cfg000066400000000000000000000016771316034351600257550ustar00rootroot00000000000000##---------------Begin: proguard configuration for Gson ---------- # Gson uses generic type information stored in a class file when working with fields. Proguard # removes such information by default, so configure it to keep all of it. -keepattributes Signature # For using GSON @Expose annotation -keepattributes *Annotation* # Gson specific classes -dontwarn sun.misc.** #-keep class com.google.gson.stream.** { *; } # Application classes that will be serialized/deserialized over Gson -keep class com.google.gson.examples.android.model.** { *; } # Prevent proguard from stripping interface information from TypeAdapterFactory, # JsonSerializer, JsonDeserializer instances (so they can be used in @JsonAdapter) -keep class * implements com.google.gson.TypeAdapterFactory -keep class * implements com.google.gson.JsonSerializer -keep class * implements com.google.gson.JsonDeserializer ##---------------End: proguard configuration for Gson ---------- gson-gson-parent-2.8.2/examples/android-proguard-example/res/000077500000000000000000000000001316034351600242275ustar00rootroot00000000000000gson-gson-parent-2.8.2/examples/android-proguard-example/res/drawable/000077500000000000000000000000001316034351600260105ustar00rootroot00000000000000gson-gson-parent-2.8.2/examples/android-proguard-example/res/drawable/icon.png000066400000000000000000000050161316034351600274500ustar00rootroot00000000000000PNG  IHDR00W IDAThY[W{fwe].ׅ@%b2&!B-IJԊԔK2/ jIIʒ1%/" .˲6Kw=NO@_>p{5T|*$W4RIJrA¸NL0u@X>d`vq}a'uhɃ{H(JLE(P5g~>Sר~;c}_ЋG&Ƈx\RU) Z)[|Y fE]~A $XE, M,$YjF%@f"d\R )3 s 'E{Ab<S +9PY^gpEPQyfL {"G_cjt&uη}YkdN=SVlSXӲ Ǝ~4tb$>j4EX,4ԣZgU3l\]Ox>:V>fb⩐ɻ59 #Dh*R$> & Aϕ=Hi+v^$1$1džwGPUH&$,7~ɩ5d|OEBr!5-[tQ F׊.MaSQS݊ G쵘բc#=JC`~%mִn;`)"!1WU}ظ\Pۼf[No*_vI1k%;v쿻:;;VzG{4 =[wWqXJK@<|΃ Y']p;Dqo?Wl+ф=w۲J 8|,-U3]Эּ(#phh9\ZnE8U['O555rr.$(G:!%XFKm$H$+W```@xE;m֙@hD7\#}K\`)=o~ƐR? *KPa|ppP/<(k7pa|o#ӇyfIK܇%,fU*5:: DR Vp@/`(ndYuzg(-Hݔr&MP 󾉕MKdB SaEld,꾱yq.ꁇGD[v"$1YFx9z /xE";>lں*L!\3  =>wzԆn41r['\c2,Ar{49 ]ݸ M x4P1^l^ssO#G%=21嶂qlkHd@,$M@rLLeE-+Z]1Xݸ'H(**7?Zz2gNX,X8Z@V(Ts8+CNQ8;w\勸PVӚb震pNykIDa |89\D.i;$wm@1W5%@5?j~՞:3 'BK-7 F8c~GeoY rڀh. ɯd6?|;U"r0þЏ]v@}ߕJn05aq^G..cRQ HJ_ p#1di=9ex>_Q{1U{RVʯqy0h糥D?หۭZ*ߡgOVzjd7ލ.:S55nP'!VRcRYpb:`E\S{qnl/Wr7Nr>XQɾ~]UZ>d K&6 FAhI@7V޲~,n/Aܕ8~Xoo$Iu9/ƻ4NB/-"^@N8?uDw c>u*}9\v1(5p J$qbx8J㝌M2(4gk,\gD aZ"ĂTʅl r!DR1á[ {DUFJY@E@3)hZ*9nH$tIENDB`gson-gson-parent-2.8.2/examples/android-proguard-example/res/layout/000077500000000000000000000000001316034351600255445ustar00rootroot00000000000000gson-gson-parent-2.8.2/examples/android-proguard-example/res/layout/main.xml000066400000000000000000000005471316034351600272200ustar00rootroot00000000000000 gson-gson-parent-2.8.2/examples/android-proguard-example/res/values/000077500000000000000000000000001316034351600255265ustar00rootroot00000000000000gson-gson-parent-2.8.2/examples/android-proguard-example/res/values/strings.xml000066400000000000000000000001721316034351600277410ustar00rootroot00000000000000 Gson Proguard Example gson-gson-parent-2.8.2/examples/android-proguard-example/src/000077500000000000000000000000001316034351600242255ustar00rootroot00000000000000gson-gson-parent-2.8.2/examples/android-proguard-example/src/com/000077500000000000000000000000001316034351600250035ustar00rootroot00000000000000gson-gson-parent-2.8.2/examples/android-proguard-example/src/com/google/000077500000000000000000000000001316034351600262575ustar00rootroot00000000000000gson-gson-parent-2.8.2/examples/android-proguard-example/src/com/google/gson/000077500000000000000000000000001316034351600272255ustar00rootroot00000000000000gson-gson-parent-2.8.2/examples/android-proguard-example/src/com/google/gson/examples/000077500000000000000000000000001316034351600310435ustar00rootroot00000000000000gson-gson-parent-2.8.2/examples/android-proguard-example/src/com/google/gson/examples/android/000077500000000000000000000000001316034351600324635ustar00rootroot00000000000000GsonProguardExampleActivity.java000066400000000000000000000041651316034351600407200ustar00rootroot00000000000000gson-gson-parent-2.8.2/examples/android-proguard-example/src/com/google/gson/examples/android/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.examples.android; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.examples.android.model.Cart; import com.google.gson.examples.android.model.LineItem; /** * Activity class illustrating how to use proguard with Gson * * @author Inderjeet Singh */ public class GsonProguardExampleActivity extends Activity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); TextView tv = (TextView) findViewById(R.id.tv); Gson gson = new Gson(); Cart cart = buildCart(); StringBuilder sb = new StringBuilder(); sb.append("Gson.toJson() example: \n"); sb.append(" Cart Object: ").append(cart).append("\n"); sb.append(" Cart JSON: ").append(gson.toJson(cart)).append("\n"); sb.append("\n\nGson.fromJson() example: \n"); String json = "{buyer:'Happy Camper',creditCard:'4111-1111-1111-1111'," + "lineItems:[{name:'nails',priceInMicros:100000,quantity:100,currencyCode:'USD'}]}"; sb.append("Cart JSON: ").append(json).append("\n"); sb.append("Cart Object: ").append(gson.fromJson(json, Cart.class)).append("\n"); tv.setText(sb.toString()); tv.invalidate(); } private Cart buildCart() { List lineItems = new ArrayList(); lineItems.add(new LineItem("hammer", 1, 12000000, "USD")); return new Cart(lineItems, "Happy Buyer", "4111-1111-1111-1111"); } } gson-gson-parent-2.8.2/examples/android-proguard-example/src/com/google/gson/examples/android/model/000077500000000000000000000000001316034351600335635ustar00rootroot00000000000000Cart.java000066400000000000000000000057431316034351600352510ustar00rootroot00000000000000gson-gson-parent-2.8.2/examples/android-proguard-example/src/com/google/gson/examples/android/model/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.examples.android.model; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.WildcardType; import java.util.List; import com.google.gson.annotations.SerializedName; /** * A model object representing a cart that can be posted to an order-processing server * * @author Inderjeet Singh */ public class Cart { public final List lineItems; @SerializedName("buyer") private final String buyerName; private final String creditCard; public Cart(List lineItems, String buyerName, String creditCard) { this.lineItems = lineItems; this.buyerName = buyerName; this.creditCard = creditCard; } public List getLineItems() { return lineItems; } public String getBuyerName() { return buyerName; } public String getCreditCard() { return creditCard; } @Override public String toString() { StringBuilder itemsText = new StringBuilder(); boolean first = true; if (lineItems != null) { try { Class fieldType = Cart.class.getField("lineItems").getType(); System.out.println("LineItems CLASS: " + getSimpleTypeName(fieldType)); } catch (SecurityException e) { } catch (NoSuchFieldException e) { } for (LineItem item : lineItems) { if (first) { first = false; } else { itemsText.append("; "); } itemsText.append(item); } } return "[BUYER: " + buyerName + "; CC: " + creditCard + "; " + "LINE_ITEMS: " + itemsText.toString() + "]"; } @SuppressWarnings("unchecked") public static String getSimpleTypeName(Type type) { if (type == null) { return "null"; } if (type instanceof Class) { return ((Class)type).getSimpleName(); } else if (type instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) type; StringBuilder sb = new StringBuilder(getSimpleTypeName(pType.getRawType())); sb.append('<'); boolean first = true; for (Type argumentType : pType.getActualTypeArguments()) { if (first) { first = false; } else { sb.append(','); } sb.append(getSimpleTypeName(argumentType)); } sb.append('>'); return sb.toString(); } else if (type instanceof WildcardType) { return "?"; } return type.toString(); } } LineItem.java000066400000000000000000000030221316034351600360520ustar00rootroot00000000000000gson-gson-parent-2.8.2/examples/android-proguard-example/src/com/google/gson/examples/android/model/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.examples.android.model; /** * A line item in a cart. This is not a rest resource, just a dependent object * * @author Inderjeet Singh */ public class LineItem { private final String name; private final int quantity; private final long priceInMicros; private final String currencyCode; public LineItem(String name, int quantity, long priceInMicros, String currencyCode) { this.name = name; this.quantity = quantity; this.priceInMicros = priceInMicros; this.currencyCode = currencyCode; } public String getName() { return name; } public int getQuantity() { return quantity; } public long getPriceInMicros() { return priceInMicros; } public String getCurrencyCode() { return currencyCode; } @Override public String toString() { return String.format("(item: %s, qty: %s, price: %.2f %s)", name, quantity, priceInMicros / 1000000d, currencyCode); } } gson-gson-parent-2.8.2/extras/000077500000000000000000000000001316034351600162345ustar00rootroot00000000000000gson-gson-parent-2.8.2/extras/pom.xml000066400000000000000000000136371316034351600175630ustar00rootroot00000000000000 4.0.0 com.google.code.gson gson-extras jar 1.0-SNAPSHOT 2008 Gson Extras org.sonatype.oss oss-parent 9 http://code.google.com/p/google-gson/ Google Gson grab bag of utilities, type adapters, etc. UTF-8 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt repo scm:svn:http://google-gson.googlecode.com/svn/trunk/extras scm:svn:https://google-gson.googlecode.com/svn/trunk/extras http://google-gson.codegoogle.com/svn/trunk/extras Google Code Issue Tracking http://code.google.com/p/google-gson/issues/list Google, Inc. http://www.google.com com.google.code.gson gson 2.7 compile javax.annotation jsr250-api 1.0 junit junit 3.8.2 test release-sign-artifacts performRelease true org.apache.maven.plugins maven-gpg-plugin 1.5 sign-artifacts verify sign package org.apache.maven.plugins maven-compiler-plugin 3.5.1 1.6 1.6 org.apache.maven.plugins maven-jar-plugin 3.0.2 package jar false org.apache.maven.plugins maven-source-plugin 3.0.1 attach-sources verify jar org.apache.maven.plugins maven-javadoc-plugin 2.10.4 attach-javadocs jar http://download.oracle.com/javase/1.5.0/docs/api/ true public org.apache.maven.plugins maven-eclipse-plugin 2.10 true true ../eclipse-ws/ file:///${basedir}/../lib/gson-formatting-styles.xml org.apache.maven.plugins maven-release-plugin -DenableCiProfile=true https://google-gson.googlecode.com/svn/tags/ Inderjeet Singh Joel Leitch Google Inc. Jesse Wilson Square Inc. gson-gson-parent-2.8.2/extras/src/000077500000000000000000000000001316034351600170235ustar00rootroot00000000000000gson-gson-parent-2.8.2/extras/src/main/000077500000000000000000000000001316034351600177475ustar00rootroot00000000000000gson-gson-parent-2.8.2/extras/src/main/java/000077500000000000000000000000001316034351600206705ustar00rootroot00000000000000gson-gson-parent-2.8.2/extras/src/main/java/com/000077500000000000000000000000001316034351600214465ustar00rootroot00000000000000gson-gson-parent-2.8.2/extras/src/main/java/com/google/000077500000000000000000000000001316034351600227225ustar00rootroot00000000000000gson-gson-parent-2.8.2/extras/src/main/java/com/google/gson/000077500000000000000000000000001316034351600236705ustar00rootroot00000000000000gson-gson-parent-2.8.2/extras/src/main/java/com/google/gson/extras/000077500000000000000000000000001316034351600251765ustar00rootroot00000000000000gson-gson-parent-2.8.2/extras/src/main/java/com/google/gson/extras/examples/000077500000000000000000000000001316034351600270145ustar00rootroot00000000000000gson-gson-parent-2.8.2/extras/src/main/java/com/google/gson/extras/examples/rawcollections/000077500000000000000000000000001316034351600320445ustar00rootroot00000000000000RawCollectionsExample.java000066400000000000000000000035751316034351600371060ustar00rootroot00000000000000gson-gson-parent-2.8.2/extras/src/main/java/com/google/gson/extras/examples/rawcollections/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.extras.examples.rawcollections; import java.util.ArrayList; import java.util.Collection; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonParser; public class RawCollectionsExample { static class Event { private String name; private String source; private Event(String name, String source) { this.name = name; this.source = source; } @Override public String toString() { return String.format("(name=%s, source=%s)", name, source); } } @SuppressWarnings({ "unchecked", "rawtypes" }) public static void main(String[] args) { Gson gson = new Gson(); Collection collection = new ArrayList(); collection.add("hello"); collection.add(5); collection.add(new Event("GREETINGS", "guest")); String json = gson.toJson(collection); System.out.println("Using Gson.toJson() on a raw collection: " + json); JsonParser parser = new JsonParser(); JsonArray array = parser.parse(json).getAsJsonArray(); String message = gson.fromJson(array.get(0), String.class); int number = gson.fromJson(array.get(1), int.class); Event event = gson.fromJson(array.get(2), Event.class); System.out.printf("Using Gson.fromJson() to get: %s, %d, %s", message, number, event); } } gson-gson-parent-2.8.2/extras/src/main/java/com/google/gson/graph/000077500000000000000000000000001316034351600247715ustar00rootroot00000000000000gson-gson-parent-2.8.2/extras/src/main/java/com/google/gson/graph/GraphAdapterBuilder.java000066400000000000000000000246461316034351600315210ustar00rootroot00000000000000/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.graph; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.InstanceCreator; import com.google.gson.JsonElement; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.internal.ConstructorConstructor; import com.google.gson.internal.ObjectConstructor; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.lang.reflect.Type; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.LinkedList; import java.util.Map; import java.util.Queue; /** * Writes a graph of objects as a list of named nodes. */ // TODO: proper documentation @SuppressWarnings("rawtypes") public final class GraphAdapterBuilder { private final Map> instanceCreators; private final ConstructorConstructor constructorConstructor; public GraphAdapterBuilder() { this.instanceCreators = new HashMap>(); this.constructorConstructor = new ConstructorConstructor(instanceCreators); } public GraphAdapterBuilder addType(Type type) { final ObjectConstructor objectConstructor = constructorConstructor.get(TypeToken.get(type)); InstanceCreator instanceCreator = new InstanceCreator() { public Object createInstance(Type type) { return objectConstructor.construct(); } }; return addType(type, instanceCreator); } public GraphAdapterBuilder addType(Type type, InstanceCreator instanceCreator) { if (type == null || instanceCreator == null) { throw new NullPointerException(); } instanceCreators.put(type, instanceCreator); return this; } public void registerOn(GsonBuilder gsonBuilder) { Factory factory = new Factory(instanceCreators); gsonBuilder.registerTypeAdapterFactory(factory); for (Map.Entry> entry : instanceCreators.entrySet()) { gsonBuilder.registerTypeAdapter(entry.getKey(), factory); } } static class Factory implements TypeAdapterFactory, InstanceCreator { private final Map> instanceCreators; private final ThreadLocal graphThreadLocal = new ThreadLocal(); Factory(Map> instanceCreators) { this.instanceCreators = instanceCreators; } public TypeAdapter create(Gson gson, TypeToken type) { if (!instanceCreators.containsKey(type.getType())) { return null; } final TypeAdapter typeAdapter = gson.getDelegateAdapter(this, type); final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); return new TypeAdapter() { @Override public void write(JsonWriter out, T value) throws IOException { if (value == null) { out.nullValue(); return; } Graph graph = graphThreadLocal.get(); boolean writeEntireGraph = false; /* * We have one of two cases: * 1. We've encountered the first known object in this graph. Write * out the graph, starting with that object. * 2. We've encountered another graph object in the course of #1. * Just write out this object's name. We'll circle back to writing * out the object's value as a part of #1. */ if (graph == null) { writeEntireGraph = true; graph = new Graph(new IdentityHashMap>()); } @SuppressWarnings("unchecked") // graph.map guarantees consistency between value and T Element element = (Element) graph.map.get(value); if (element == null) { element = new Element(value, graph.nextName(), typeAdapter, null); graph.map.put(value, element); graph.queue.add(element); } if (writeEntireGraph) { graphThreadLocal.set(graph); try { out.beginObject(); Element current; while ((current = graph.queue.poll()) != null) { out.name(current.id); current.write(out); } out.endObject(); } finally { graphThreadLocal.remove(); } } else { out.value(element.id); } } @Override public T read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } /* * Again we have one of two cases: * 1. We've encountered the first known object in this graph. Read * the entire graph in as a map from names to their JsonElements. * Then convert the first JsonElement to its Java object. * 2. We've encountered another graph object in the course of #1. * Read in its name, then deserialize its value from the * JsonElement in our map. We need to do this lazily because we * don't know which TypeAdapter to use until a value is * encountered in the wild. */ String currentName = null; Graph graph = graphThreadLocal.get(); boolean readEntireGraph = false; if (graph == null) { graph = new Graph(new HashMap>()); readEntireGraph = true; // read the entire tree into memory in.beginObject(); while (in.hasNext()) { String name = in.nextName(); if (currentName == null) { currentName = name; } JsonElement element = elementAdapter.read(in); graph.map.put(name, new Element(null, name, typeAdapter, element)); } in.endObject(); } else { currentName = in.nextString(); } if (readEntireGraph) { graphThreadLocal.set(graph); } try { @SuppressWarnings("unchecked") // graph.map guarantees consistency between value and T Element element = (Element) graph.map.get(currentName); // now that we know the typeAdapter for this name, go from JsonElement to 'T' if (element.value == null) { element.typeAdapter = typeAdapter; element.read(graph); } return element.value; } finally { if (readEntireGraph) { graphThreadLocal.remove(); } } } }; } /** * Hook for the graph adapter to get a reference to a deserialized value * before that value is fully populated. This is useful to deserialize * values that directly or indirectly reference themselves: we can hand * out an instance before read() returns. * *

Gson should only ever call this method when we're expecting it to; * that is only when we've called back into Gson to deserialize a tree. */ @SuppressWarnings("unchecked") public Object createInstance(Type type) { Graph graph = graphThreadLocal.get(); if (graph == null || graph.nextCreate == null) { throw new IllegalStateException("Unexpected call to createInstance() for " + type); } InstanceCreator creator = instanceCreators.get(type); Object result = creator.createInstance(type); graph.nextCreate.value = result; graph.nextCreate = null; return result; } } static class Graph { /** * The graph elements. On serialization keys are objects (using an identity * hash map) and on deserialization keys are the string names (using a * standard hash map). */ private final Map> map; /** * The queue of elements to write during serialization. Unused during * deserialization. */ private final Queue queue = new LinkedList(); /** * The instance currently being deserialized. Used as a backdoor between * the graph traversal (which needs to know instances) and instance creators * which create them. */ private Element nextCreate; private Graph(Map> map) { this.map = map; } /** * Returns a unique name for an element to be inserted into the graph. */ public String nextName() { return "0x" + Integer.toHexString(map.size() + 1); } } /** * An element of the graph during serialization or deserialization. */ static class Element { /** * This element's name in the top level graph object. */ private final String id; /** * The value if known. During deserialization this is lazily populated. */ private T value; /** * This element's type adapter if known. During deserialization this is * lazily populated. */ private TypeAdapter typeAdapter; /** * The element to deserialize. Unused in serialization. */ private final JsonElement element; Element(T value, String id, TypeAdapter typeAdapter, JsonElement element) { this.value = value; this.id = id; this.typeAdapter = typeAdapter; this.element = element; } void write(JsonWriter out) throws IOException { typeAdapter.write(out, value); } void read(Graph graph) throws IOException { if (graph.nextCreate != null) { throw new IllegalStateException("Unexpected recursive call to read() for " + id); } graph.nextCreate = this; value = typeAdapter.fromJsonTree(element); if (value == null) { throw new IllegalStateException("non-null value deserialized to null: " + element); } } } } gson-gson-parent-2.8.2/extras/src/main/java/com/google/gson/interceptors/000077500000000000000000000000001316034351600264115ustar00rootroot00000000000000gson-gson-parent-2.8.2/extras/src/main/java/com/google/gson/interceptors/Intercept.java000066400000000000000000000040501316034351600312100ustar00rootroot00000000000000/* * Copyright (C) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.interceptors; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Use this annotation to indicate various interceptors for class instances after * they have been processed by Gson. For example, you can use it to validate an instance * after it has been deserialized from Json. * Here is an example of how this annotation is used: *

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

 * @Intercept(postDeserialize=UserValidator.class)
 * public class User {
 *   String name;
 *   String password;
 *   String emailAddress;
 * }
 *
 * public class UserValidator implements JsonPostDeserializer<User> {
 *   public void postDeserialize(User user) {
 *     // Do some checks on user
 *     if (user.name == null || user.password == null) {
 *       throw new JsonParseException("name and password are required fields.");
 *     }
 *     if (user.emailAddress == null) {
 *       emailAddress = "unknown"; // assign a default value.
 *     }
 *   }
 * }
 * 

* * @author Inderjeet Singh */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface Intercept { /** * Specify the class that provides the methods that should be invoked after an instance * has been deserialized. */ @SuppressWarnings("rawtypes") public Class postDeserialize(); } gson-gson-parent-2.8.2/extras/src/main/java/com/google/gson/interceptors/InterceptorFactory.java000066400000000000000000000030301316034351600330760ustar00rootroot00000000000000package com.google.gson.interceptors; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; /** * A type adapter factory that implements {@code @Intercept}. */ public final class InterceptorFactory implements TypeAdapterFactory { public TypeAdapter create(Gson gson, TypeToken type) { Intercept intercept = type.getRawType().getAnnotation(Intercept.class); if (intercept == null) { return null; } TypeAdapter delegate = gson.getDelegateAdapter(this, type); return new InterceptorAdapter(delegate, intercept); } static class InterceptorAdapter extends TypeAdapter { private final TypeAdapter delegate; private final JsonPostDeserializer postDeserializer; @SuppressWarnings("unchecked") // ? public InterceptorAdapter(TypeAdapter delegate, Intercept intercept) { try { this.delegate = delegate; this.postDeserializer = intercept.postDeserialize().newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void write(JsonWriter out, T value) throws IOException { delegate.write(out, value); } @Override public T read(JsonReader in) throws IOException { T result = delegate.read(in); postDeserializer.postDeserialize(result); return result; } } } gson-gson-parent-2.8.2/extras/src/main/java/com/google/gson/interceptors/JsonPostDeserializer.java000066400000000000000000000021351316034351600333770ustar00rootroot00000000000000/* * Copyright (C) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.interceptors; import com.google.gson.InstanceCreator; /** * This interface is implemented by a class that wishes to inspect or modify an object * after it has been deserialized. You must define a no-args constructor or register an * {@link InstanceCreator} for such a class. * * @author Inderjeet Singh */ public interface JsonPostDeserializer { /** * This method is called by Gson after the object has been deserialized from Json. */ public void postDeserialize(T object); } gson-gson-parent-2.8.2/extras/src/main/java/com/google/gson/typeadapters/000077500000000000000000000000001316034351600263755ustar00rootroot00000000000000PostConstructAdapterFactory.java000066400000000000000000000054311316034351600346470ustar00rootroot00000000000000gson-gson-parent-2.8.2/extras/src/main/java/com/google/gson/typeadapters/* * Copyright (C) 2016 Gson Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.typeadapters; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import javax.annotation.PostConstruct; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; public class PostConstructAdapterFactory implements TypeAdapterFactory { // copied from https://gist.github.com/swankjesse/20df26adaf639ed7fd160f145a0b661a @Override public TypeAdapter create(Gson gson, TypeToken type) { for (Class t = type.getRawType(); (t != Object.class) && (t.getSuperclass() != null); t = t.getSuperclass()) { for (Method m : t.getDeclaredMethods()) { if (m.isAnnotationPresent(PostConstruct.class)) { m.setAccessible(true); TypeAdapter delegate = gson.getDelegateAdapter(this, type); return new PostConstructAdapter(delegate, m); } } } return null; } final static class PostConstructAdapter extends TypeAdapter { private final TypeAdapter delegate; private final Method method; public PostConstructAdapter(TypeAdapter delegate, Method method) { this.delegate = delegate; this.method = method; } @Override public T read(JsonReader in) throws IOException { T result = delegate.read(in); if (result != null) { try { method.invoke(result); } catch (IllegalAccessException e) { throw new AssertionError(); } catch (InvocationTargetException e) { if (e.getCause() instanceof RuntimeException) throw (RuntimeException) e.getCause(); throw new RuntimeException(e.getCause()); } } return result; } @Override public void write(JsonWriter out, T value) throws IOException { delegate.write(out, value); } } } RuntimeTypeAdapterFactory.java000066400000000000000000000215571316034351600343110ustar00rootroot00000000000000gson-gson-parent-2.8.2/extras/src/main/java/com/google/gson/typeadapters/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.typeadapters; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.internal.Streams; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; /** * Adapts values whose runtime type may differ from their declaration type. This * is necessary when a field's type is not the same type that GSON should create * when deserializing that field. For example, consider these types: *
   {@code
 *   abstract class Shape {
 *     int x;
 *     int y;
 *   }
 *   class Circle extends Shape {
 *     int radius;
 *   }
 *   class Rectangle extends Shape {
 *     int width;
 *     int height;
 *   }
 *   class Diamond extends Shape {
 *     int width;
 *     int height;
 *   }
 *   class Drawing {
 *     Shape bottomShape;
 *     Shape topShape;
 *   }
 * }
*

Without additional type information, the serialized JSON is ambiguous. Is * the bottom shape in this drawing a rectangle or a diamond?

   {@code
 *   {
 *     "bottomShape": {
 *       "width": 10,
 *       "height": 5,
 *       "x": 0,
 *       "y": 0
 *     },
 *     "topShape": {
 *       "radius": 2,
 *       "x": 4,
 *       "y": 1
 *     }
 *   }}
* This class addresses this problem by adding type information to the * serialized JSON and honoring that type information when the JSON is * deserialized:
   {@code
 *   {
 *     "bottomShape": {
 *       "type": "Diamond",
 *       "width": 10,
 *       "height": 5,
 *       "x": 0,
 *       "y": 0
 *     },
 *     "topShape": {
 *       "type": "Circle",
 *       "radius": 2,
 *       "x": 4,
 *       "y": 1
 *     }
 *   }}
* Both the type field name ({@code "type"}) and the type labels ({@code * "Rectangle"}) are configurable. * *

Registering Types

* Create a {@code RuntimeTypeAdapterFactory} by passing the base type and type field * name to the {@link #of} factory method. If you don't supply an explicit type * field name, {@code "type"} will be used.
   {@code
 *   RuntimeTypeAdapterFactory shapeAdapterFactory
 *       = RuntimeTypeAdapterFactory.of(Shape.class, "type");
 * }
* Next register all of your subtypes. Every subtype must be explicitly * registered. This protects your application from injection attacks. If you * don't supply an explicit type label, the type's simple name will be used. *
   {@code
 *   shapeAdapter.registerSubtype(Rectangle.class, "Rectangle");
 *   shapeAdapter.registerSubtype(Circle.class, "Circle");
 *   shapeAdapter.registerSubtype(Diamond.class, "Diamond");
 * }
* Finally, register the type adapter factory in your application's GSON builder: *
   {@code
 *   Gson gson = new GsonBuilder()
 *       .registerTypeAdapterFactory(shapeAdapterFactory)
 *       .create();
 * }
* Like {@code GsonBuilder}, this API supports chaining:
   {@code
 *   RuntimeTypeAdapterFactory shapeAdapterFactory = RuntimeTypeAdapterFactory.of(Shape.class)
 *       .registerSubtype(Rectangle.class)
 *       .registerSubtype(Circle.class)
 *       .registerSubtype(Diamond.class);
 * }
*/ public final class RuntimeTypeAdapterFactory implements TypeAdapterFactory { private final Class baseType; private final String typeFieldName; private final Map> labelToSubtype = new LinkedHashMap>(); private final Map, String> subtypeToLabel = new LinkedHashMap, String>(); private RuntimeTypeAdapterFactory(Class baseType, String typeFieldName) { if (typeFieldName == null || baseType == null) { throw new NullPointerException(); } this.baseType = baseType; this.typeFieldName = typeFieldName; } /** * Creates a new runtime type adapter using for {@code baseType} using {@code * typeFieldName} as the type field name. Type field names are case sensitive. */ public static RuntimeTypeAdapterFactory of(Class baseType, String typeFieldName) { return new RuntimeTypeAdapterFactory(baseType, typeFieldName); } /** * Creates a new runtime type adapter for {@code baseType} using {@code "type"} as * the type field name. */ public static RuntimeTypeAdapterFactory of(Class baseType) { return new RuntimeTypeAdapterFactory(baseType, "type"); } /** * Registers {@code type} identified by {@code label}. Labels are case * sensitive. * * @throws IllegalArgumentException if either {@code type} or {@code label} * have already been registered on this type adapter. */ public RuntimeTypeAdapterFactory registerSubtype(Class type, String label) { if (type == null || label == null) { throw new NullPointerException(); } if (subtypeToLabel.containsKey(type) || labelToSubtype.containsKey(label)) { throw new IllegalArgumentException("types and labels must be unique"); } labelToSubtype.put(label, type); subtypeToLabel.put(type, label); return this; } /** * Registers {@code type} identified by its {@link Class#getSimpleName simple * name}. Labels are case sensitive. * * @throws IllegalArgumentException if either {@code type} or its simple name * have already been registered on this type adapter. */ public RuntimeTypeAdapterFactory registerSubtype(Class type) { return registerSubtype(type, type.getSimpleName()); } public TypeAdapter create(Gson gson, TypeToken type) { if (type.getRawType() != baseType) { return null; } final Map> labelToDelegate = new LinkedHashMap>(); final Map, TypeAdapter> subtypeToDelegate = new LinkedHashMap, TypeAdapter>(); for (Map.Entry> entry : labelToSubtype.entrySet()) { TypeAdapter delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue())); labelToDelegate.put(entry.getKey(), delegate); subtypeToDelegate.put(entry.getValue(), delegate); } return new TypeAdapter() { @Override public R read(JsonReader in) throws IOException { JsonElement jsonElement = Streams.parse(in); JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName); if (labelJsonElement == null) { throw new JsonParseException("cannot deserialize " + baseType + " because it does not define a field named " + typeFieldName); } String label = labelJsonElement.getAsString(); @SuppressWarnings("unchecked") // registration requires that subtype extends T TypeAdapter delegate = (TypeAdapter) labelToDelegate.get(label); if (delegate == null) { throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label + "; did you forget to register a subtype?"); } return delegate.fromJsonTree(jsonElement); } @Override public void write(JsonWriter out, R value) throws IOException { Class srcType = value.getClass(); String label = subtypeToLabel.get(srcType); @SuppressWarnings("unchecked") // registration requires that subtype extends T TypeAdapter delegate = (TypeAdapter) subtypeToDelegate.get(srcType); if (delegate == null) { throw new JsonParseException("cannot serialize " + srcType.getName() + "; did you forget to register a subtype?"); } JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject(); if (jsonObject.has(typeFieldName)) { throw new JsonParseException("cannot serialize " + srcType.getName() + " because it already defines a field named " + typeFieldName); } JsonObject clone = new JsonObject(); clone.add(typeFieldName, new JsonPrimitive(label)); for (Map.Entry e : jsonObject.entrySet()) { clone.add(e.getKey(), e.getValue()); } Streams.write(clone, out); } }.nullSafe(); } } gson-gson-parent-2.8.2/extras/src/main/java/com/google/gson/typeadapters/UtcDateTypeAdapter.java000066400000000000000000000236641316034351600327470ustar00rootroot00000000000000/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.typeadapters; import java.io.IOException; import java.text.ParseException; import java.text.ParsePosition; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; public final class UtcDateTypeAdapter extends TypeAdapter { private final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("UTC"); @Override public void write(JsonWriter out, Date date) throws IOException { if (date == null) { out.nullValue(); } else { String value = format(date, true, UTC_TIME_ZONE); out.value(value); } } @Override public Date read(JsonReader in) throws IOException { try { switch (in.peek()) { case NULL: in.nextNull(); return null; default: String date = in.nextString(); // Instead of using iso8601Format.parse(value), we use Jackson's date parsing // This is because Android doesn't support XXX because it is JDK 1.6 return parse(date, new ParsePosition(0)); } } catch (ParseException e) { throw new JsonParseException(e); } } // Date parsing code from Jackson databind ISO8601Utils.java // https://github.com/FasterXML/jackson-databind/blob/master/src/main/java/com/fasterxml/jackson/databind/util/ISO8601Utils.java private static final String GMT_ID = "GMT"; /** * Format date into yyyy-MM-ddThh:mm:ss[.sss][Z|[+-]hh:mm] * * @param date the date to format * @param millis true to include millis precision otherwise false * @param tz timezone to use for the formatting (GMT will produce 'Z') * @return the date formatted as yyyy-MM-ddThh:mm:ss[.sss][Z|[+-]hh:mm] */ private static String format(Date date, boolean millis, TimeZone tz) { Calendar calendar = new GregorianCalendar(tz, Locale.US); calendar.setTime(date); // estimate capacity of buffer as close as we can (yeah, that's pedantic ;) int capacity = "yyyy-MM-ddThh:mm:ss".length(); capacity += millis ? ".sss".length() : 0; capacity += tz.getRawOffset() == 0 ? "Z".length() : "+hh:mm".length(); StringBuilder formatted = new StringBuilder(capacity); padInt(formatted, calendar.get(Calendar.YEAR), "yyyy".length()); formatted.append('-'); padInt(formatted, calendar.get(Calendar.MONTH) + 1, "MM".length()); formatted.append('-'); padInt(formatted, calendar.get(Calendar.DAY_OF_MONTH), "dd".length()); formatted.append('T'); padInt(formatted, calendar.get(Calendar.HOUR_OF_DAY), "hh".length()); formatted.append(':'); padInt(formatted, calendar.get(Calendar.MINUTE), "mm".length()); formatted.append(':'); padInt(formatted, calendar.get(Calendar.SECOND), "ss".length()); if (millis) { formatted.append('.'); padInt(formatted, calendar.get(Calendar.MILLISECOND), "sss".length()); } int offset = tz.getOffset(calendar.getTimeInMillis()); if (offset != 0) { int hours = Math.abs((offset / (60 * 1000)) / 60); int minutes = Math.abs((offset / (60 * 1000)) % 60); formatted.append(offset < 0 ? '-' : '+'); padInt(formatted, hours, "hh".length()); formatted.append(':'); padInt(formatted, minutes, "mm".length()); } else { formatted.append('Z'); } return formatted.toString(); } /** * Zero pad a number to a specified length * * @param buffer buffer to use for padding * @param value the integer value to pad if necessary. * @param length the length of the string we should zero pad */ private static void padInt(StringBuilder buffer, int value, int length) { String strValue = Integer.toString(value); for (int i = length - strValue.length(); i > 0; i--) { buffer.append('0'); } buffer.append(strValue); } /** * Parse a date from ISO-8601 formatted string. It expects a format * [yyyy-MM-dd|yyyyMMdd][T(hh:mm[:ss[.sss]]|hhmm[ss[.sss]])]?[Z|[+-]hh:mm]] * * @param date ISO string to parse in the appropriate format. * @param pos The position to start parsing from, updated to where parsing stopped. * @return the parsed date * @throws ParseException if the date is not in the appropriate format */ private static Date parse(String date, ParsePosition pos) throws ParseException { Exception fail = null; try { int offset = pos.getIndex(); // extract year int year = parseInt(date, offset, offset += 4); if (checkOffset(date, offset, '-')) { offset += 1; } // extract month int month = parseInt(date, offset, offset += 2); if (checkOffset(date, offset, '-')) { offset += 1; } // extract day int day = parseInt(date, offset, offset += 2); // default time value int hour = 0; int minutes = 0; int seconds = 0; int milliseconds = 0; // always use 0 otherwise returned date will include millis of current time if (checkOffset(date, offset, 'T')) { // extract hours, minutes, seconds and milliseconds hour = parseInt(date, offset += 1, offset += 2); if (checkOffset(date, offset, ':')) { offset += 1; } minutes = parseInt(date, offset, offset += 2); if (checkOffset(date, offset, ':')) { offset += 1; } // second and milliseconds can be optional if (date.length() > offset) { char c = date.charAt(offset); if (c != 'Z' && c != '+' && c != '-') { seconds = parseInt(date, offset, offset += 2); // milliseconds can be optional in the format if (checkOffset(date, offset, '.')) { milliseconds = parseInt(date, offset += 1, offset += 3); } } } } // extract timezone String timezoneId; if (date.length() <= offset) { throw new IllegalArgumentException("No time zone indicator"); } char timezoneIndicator = date.charAt(offset); if (timezoneIndicator == '+' || timezoneIndicator == '-') { String timezoneOffset = date.substring(offset); timezoneId = GMT_ID + timezoneOffset; offset += timezoneOffset.length(); } else if (timezoneIndicator == 'Z') { timezoneId = GMT_ID; offset += 1; } else { throw new IndexOutOfBoundsException("Invalid time zone indicator " + timezoneIndicator); } TimeZone timezone = TimeZone.getTimeZone(timezoneId); if (!timezone.getID().equals(timezoneId)) { throw new IndexOutOfBoundsException(); } Calendar calendar = new GregorianCalendar(timezone); calendar.setLenient(false); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month - 1); calendar.set(Calendar.DAY_OF_MONTH, day); calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, minutes); calendar.set(Calendar.SECOND, seconds); calendar.set(Calendar.MILLISECOND, milliseconds); pos.setIndex(offset); return calendar.getTime(); // If we get a ParseException it'll already have the right message/offset. // Other exception types can convert here. } catch (IndexOutOfBoundsException e) { fail = e; } catch (NumberFormatException e) { fail = e; } catch (IllegalArgumentException e) { fail = e; } String input = (date == null) ? null : ("'" + date + "'"); throw new ParseException("Failed to parse date [" + input + "]: " + fail.getMessage(), pos.getIndex()); } /** * Check if the expected character exist at the given offset in the value. * * @param value the string to check at the specified offset * @param offset the offset to look for the expected character * @param expected the expected character * @return true if the expected character exist at the given offset */ private static boolean checkOffset(String value, int offset, char expected) { return (offset < value.length()) && (value.charAt(offset) == expected); } /** * Parse an integer located between 2 given offsets in a string * * @param value the string to parse * @param beginIndex the start index for the integer in the string * @param endIndex the end index for the integer in the string * @return the int * @throws NumberFormatException if the value is not a number */ private static int parseInt(String value, int beginIndex, int endIndex) throws NumberFormatException { if (beginIndex < 0 || endIndex > value.length() || beginIndex > endIndex) { throw new NumberFormatException(value); } // use same logic as in Integer.parseInt() but less generic we're not supporting negative values int i = beginIndex; int result = 0; int digit; if (i < endIndex) { digit = Character.digit(value.charAt(i++), 10); if (digit < 0) { throw new NumberFormatException("Invalid number: " + value); } result = -digit; } while (i < endIndex) { digit = Character.digit(value.charAt(i++), 10); if (digit < 0) { throw new NumberFormatException("Invalid number: " + value); } result *= 10; result -= digit; } return -result; } } gson-gson-parent-2.8.2/extras/src/test/000077500000000000000000000000001316034351600200025ustar00rootroot00000000000000gson-gson-parent-2.8.2/extras/src/test/java/000077500000000000000000000000001316034351600207235ustar00rootroot00000000000000gson-gson-parent-2.8.2/extras/src/test/java/com/000077500000000000000000000000001316034351600215015ustar00rootroot00000000000000gson-gson-parent-2.8.2/extras/src/test/java/com/google/000077500000000000000000000000001316034351600227555ustar00rootroot00000000000000gson-gson-parent-2.8.2/extras/src/test/java/com/google/gson/000077500000000000000000000000001316034351600237235ustar00rootroot00000000000000gson-gson-parent-2.8.2/extras/src/test/java/com/google/gson/graph/000077500000000000000000000000001316034351600250245ustar00rootroot00000000000000gson-gson-parent-2.8.2/extras/src/test/java/com/google/gson/graph/GraphAdapterBuilderTest.java000066400000000000000000000144531316034351600324070ustar00rootroot00000000000000/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.graph; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.List; import junit.framework.TestCase; public final class GraphAdapterBuilderTest extends TestCase { public void testSerialization() { Roshambo rock = new Roshambo("ROCK"); Roshambo scissors = new Roshambo("SCISSORS"); Roshambo paper = new Roshambo("PAPER"); rock.beats = scissors; scissors.beats = paper; paper.beats = rock; GsonBuilder gsonBuilder = new GsonBuilder(); new GraphAdapterBuilder() .addType(Roshambo.class) .registerOn(gsonBuilder); Gson gson = gsonBuilder.create(); assertEquals("{'0x1':{'name':'ROCK','beats':'0x2'}," + "'0x2':{'name':'SCISSORS','beats':'0x3'}," + "'0x3':{'name':'PAPER','beats':'0x1'}}", gson.toJson(rock).replace('"', '\'')); } public void testDeserialization() { String json = "{'0x1':{'name':'ROCK','beats':'0x2'}," + "'0x2':{'name':'SCISSORS','beats':'0x3'}," + "'0x3':{'name':'PAPER','beats':'0x1'}}"; GsonBuilder gsonBuilder = new GsonBuilder(); new GraphAdapterBuilder() .addType(Roshambo.class) .registerOn(gsonBuilder); Gson gson = gsonBuilder.create(); Roshambo rock = gson.fromJson(json, Roshambo.class); assertEquals("ROCK", rock.name); Roshambo scissors = rock.beats; assertEquals("SCISSORS", scissors.name); Roshambo paper = scissors.beats; assertEquals("PAPER", paper.name); assertSame(rock, paper.beats); } public void testSerializationDirectSelfReference() { Roshambo suicide = new Roshambo("SUICIDE"); suicide.beats = suicide; GsonBuilder gsonBuilder = new GsonBuilder(); new GraphAdapterBuilder() .addType(Roshambo.class) .registerOn(gsonBuilder); Gson gson = gsonBuilder.create(); assertEquals("{'0x1':{'name':'SUICIDE','beats':'0x1'}}", gson.toJson(suicide).replace('"', '\'')); } public void testDeserializationDirectSelfReference() { String json = "{'0x1':{'name':'SUICIDE','beats':'0x1'}}"; GsonBuilder gsonBuilder = new GsonBuilder(); new GraphAdapterBuilder() .addType(Roshambo.class) .registerOn(gsonBuilder); Gson gson = gsonBuilder.create(); Roshambo suicide = gson.fromJson(json, Roshambo.class); assertEquals("SUICIDE", suicide.name); assertSame(suicide, suicide.beats); } public void testSerializeListOfLists() { Type listOfListsType = new TypeToken>>() {}.getType(); Type listOfAnyType = new TypeToken>() {}.getType(); List> listOfLists = new ArrayList>(); listOfLists.add(listOfLists); listOfLists.add(new ArrayList()); GsonBuilder gsonBuilder = new GsonBuilder(); new GraphAdapterBuilder() .addType(listOfListsType) .addType(listOfAnyType) .registerOn(gsonBuilder); Gson gson = gsonBuilder.create(); String json = gson.toJson(listOfLists, listOfListsType); assertEquals("{'0x1':['0x1','0x2'],'0x2':[]}", json.replace('"', '\'')); } public void testDeserializeListOfLists() { Type listOfAnyType = new TypeToken>() {}.getType(); Type listOfListsType = new TypeToken>>() {}.getType(); GsonBuilder gsonBuilder = new GsonBuilder(); new GraphAdapterBuilder() .addType(listOfListsType) .addType(listOfAnyType) .registerOn(gsonBuilder); Gson gson = gsonBuilder.create(); List> listOfLists = gson.fromJson("{'0x1':['0x1','0x2'],'0x2':[]}", listOfListsType); assertEquals(2, listOfLists.size()); assertSame(listOfLists, listOfLists.get(0)); assertEquals(Collections.emptyList(), listOfLists.get(1)); } public void testSerializationWithMultipleTypes() { Company google = new Company("Google"); new Employee("Jesse", google); new Employee("Joel", google); GsonBuilder gsonBuilder = new GsonBuilder(); new GraphAdapterBuilder() .addType(Company.class) .addType(Employee.class) .registerOn(gsonBuilder); Gson gson = gsonBuilder.create(); assertEquals("{'0x1':{'name':'Google','employees':['0x2','0x3']}," + "'0x2':{'name':'Jesse','company':'0x1'}," + "'0x3':{'name':'Joel','company':'0x1'}}", gson.toJson(google).replace('"', '\'')); } public void testDeserializationWithMultipleTypes() { GsonBuilder gsonBuilder = new GsonBuilder(); new GraphAdapterBuilder() .addType(Company.class) .addType(Employee.class) .registerOn(gsonBuilder); Gson gson = gsonBuilder.create(); String json = "{'0x1':{'name':'Google','employees':['0x2','0x3']}," + "'0x2':{'name':'Jesse','company':'0x1'}," + "'0x3':{'name':'Joel','company':'0x1'}}"; Company company = gson.fromJson(json, Company.class); assertEquals("Google", company.name); Employee jesse = company.employees.get(0); assertEquals("Jesse", jesse.name); assertEquals(company, jesse.company); Employee joel = company.employees.get(1); assertEquals("Joel", joel.name); assertEquals(company, joel.company); } static class Roshambo { String name; Roshambo beats; Roshambo(String name) { this.name = name; } } static class Employee { final String name; final Company company; Employee(String name, Company company) { this.name = name; this.company = company; this.company.employees.add(this); } } static class Company { final String name; final List employees = new ArrayList(); Company(String name) { this.name = name; } } } gson-gson-parent-2.8.2/extras/src/test/java/com/google/gson/interceptors/000077500000000000000000000000001316034351600264445ustar00rootroot00000000000000gson-gson-parent-2.8.2/extras/src/test/java/com/google/gson/interceptors/InterceptorTest.java000066400000000000000000000133301316034351600324450ustar00rootroot00000000000000/* * Copyright (C) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.interceptors; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.JsonSyntaxException; import com.google.gson.TypeAdapter; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.lang.reflect.Type; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Map.Entry; import junit.framework.TestCase; /** * Unit tests for {@link Intercept} and {@link JsonPostDeserializer}. * * @author Inderjeet Singh */ public final class InterceptorTest extends TestCase { private Gson gson; @Override public void setUp() throws Exception { super.setUp(); this.gson = new GsonBuilder() .registerTypeAdapterFactory(new InterceptorFactory()) .enableComplexMapKeySerialization() .create(); } public void testExceptionsPropagated() { try { gson.fromJson("{}", User.class); fail(); } catch (JsonParseException expected) {} } public void testTopLevelClass() { User user = gson.fromJson("{name:'bob',password:'pwd'}", User.class); assertEquals(User.DEFAULT_EMAIL, user.email); } public void testList() { List list = gson.fromJson("[{name:'bob',password:'pwd'}]", new TypeToken>(){}.getType()); User user = list.get(0); assertEquals(User.DEFAULT_EMAIL, user.email); } public void testCollection() { Collection list = gson.fromJson("[{name:'bob',password:'pwd'}]", new TypeToken>(){}.getType()); User user = list.iterator().next(); assertEquals(User.DEFAULT_EMAIL, user.email); } public void testMapKeyAndValues() { Type mapType = new TypeToken>(){}.getType(); try { gson.fromJson("[[{name:'bob',password:'pwd'},{}]]", mapType); fail(); } catch (JsonSyntaxException expected) {} Map map = gson.fromJson("[[{name:'bob',password:'pwd'},{city:'Mountain View',state:'CA',zip:'94043'}]]", mapType); Entry entry = map.entrySet().iterator().next(); assertEquals(User.DEFAULT_EMAIL, entry.getKey().email); assertEquals(Address.DEFAULT_FIRST_LINE, entry.getValue().firstLine); } public void testField() { UserGroup userGroup = gson.fromJson("{user:{name:'bob',password:'pwd'}}", UserGroup.class); assertEquals(User.DEFAULT_EMAIL, userGroup.user.email); } public void testCustomTypeAdapter() { Gson gson = new GsonBuilder() .registerTypeAdapter(User.class, new TypeAdapter() { @Override public void write(JsonWriter out, User value) throws IOException { throw new UnsupportedOperationException(); } @Override public User read(JsonReader in) throws IOException { in.beginObject(); in.nextName(); String name = in.nextString(); in.nextName(); String password = in.nextString(); in.endObject(); return new User(name, password); } }) .registerTypeAdapterFactory(new InterceptorFactory()) .create(); UserGroup userGroup = gson.fromJson("{user:{name:'bob',password:'pwd'}}", UserGroup.class); assertEquals(User.DEFAULT_EMAIL, userGroup.user.email); } public void testDirectInvocationOfTypeAdapter() throws Exception { TypeAdapter adapter = gson.getAdapter(UserGroup.class); UserGroup userGroup = adapter.fromJson("{\"user\":{\"name\":\"bob\",\"password\":\"pwd\"}}"); assertEquals(User.DEFAULT_EMAIL, userGroup.user.email); } @SuppressWarnings("unused") private static final class UserGroup { User user; String city; } @Intercept(postDeserialize = UserValidator.class) @SuppressWarnings("unused") private static final class User { static final String DEFAULT_EMAIL = "invalid@invalid.com"; String name; String password; String email; Address address; public User(String name, String password) { this.name = name; this.password = password; } } public static final class UserValidator implements JsonPostDeserializer { public void postDeserialize(User user) { if (user.name == null || user.password == null) { throw new JsonSyntaxException("name and password are required fields."); } if (user.email == null) user.email = User.DEFAULT_EMAIL; } } @Intercept(postDeserialize = AddressValidator.class) @SuppressWarnings("unused") private static final class Address { static final String DEFAULT_FIRST_LINE = "unknown"; String firstLine; String secondLine; String city; String state; String zip; } public static final class AddressValidator implements JsonPostDeserializer
{ public void postDeserialize(Address address) { if (address.city == null || address.state == null || address.zip == null) { throw new JsonSyntaxException("Address city, state and zip are required fields."); } if (address.firstLine == null) address.firstLine = Address.DEFAULT_FIRST_LINE; } } } gson-gson-parent-2.8.2/extras/src/test/java/com/google/gson/typeadapters/000077500000000000000000000000001316034351600264305ustar00rootroot00000000000000PostConstructAdapterFactoryTest.java000066400000000000000000000074531316034351600355500ustar00rootroot00000000000000gson-gson-parent-2.8.2/extras/src/test/java/com/google/gson/typeadapters/* * Copyright (C) 2016 Gson Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.typeadapters; import javax.annotation.PostConstruct; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import junit.framework.TestCase; import java.util.Arrays; import java.util.List; public class PostConstructAdapterFactoryTest extends TestCase { public void test() throws Exception { Gson gson = new GsonBuilder() .registerTypeAdapterFactory(new PostConstructAdapterFactory()) .create(); gson.fromJson("{\"bread\": \"white\", \"cheese\": \"cheddar\"}", Sandwich.class); try { gson.fromJson("{\"bread\": \"cheesey bread\", \"cheese\": \"swiss\"}", Sandwich.class); fail(); } catch (IllegalArgumentException expected) { assertEquals("too cheesey", expected.getMessage()); } } public void testList() { MultipleSandwiches sandwiches = new MultipleSandwiches(Arrays.asList( new Sandwich("white", "cheddar"), new Sandwich("whole wheat", "swiss"))); Gson gson = new GsonBuilder().registerTypeAdapterFactory(new PostConstructAdapterFactory()).create(); // Throws NullPointerException without the fix in https://github.com/google/gson/pull/1103 String json = gson.toJson(sandwiches); assertEquals("{\"sandwiches\":[{\"bread\":\"white\",\"cheese\":\"cheddar\"},{\"bread\":\"whole wheat\",\"cheese\":\"swiss\"}]}", json); MultipleSandwiches sandwichesFromJson = gson.fromJson(json, MultipleSandwiches.class); assertEquals(sandwiches, sandwichesFromJson); } static class Sandwich { public String bread; public String cheese; public Sandwich(String bread, String cheese) { this.bread = bread; this.cheese = cheese; } @PostConstruct private void validate() { if (bread.equals("cheesey bread") && cheese != null) { throw new IllegalArgumentException("too cheesey"); } } public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof Sandwich)) { return false; } final Sandwich other = (Sandwich) o; if (this.bread == null ? other.bread != null : !this.bread.equals(other.bread)) { return false; } if (this.cheese == null ? other.cheese != null : !this.cheese.equals(other.cheese)) { return false; } return true; } } static class MultipleSandwiches { public List sandwiches; public MultipleSandwiches(List sandwiches) { this.sandwiches = sandwiches; } public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof MultipleSandwiches)) { return false; } final MultipleSandwiches other = (MultipleSandwiches) o; if (this.sandwiches == null ? other.sandwiches != null : !this.sandwiches.equals(other.sandwiches)) { return false; } return true; } } } RuntimeTypeAdapterFactoryTest.java000066400000000000000000000155271316034351600352040ustar00rootroot00000000000000gson-gson-parent-2.8.2/extras/src/test/java/com/google/gson/typeadapters/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.typeadapters; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapterFactory; import junit.framework.TestCase; public final class RuntimeTypeAdapterFactoryTest extends TestCase { public void testRuntimeTypeAdapter() { RuntimeTypeAdapterFactory rta = RuntimeTypeAdapterFactory.of( BillingInstrument.class) .registerSubtype(CreditCard.class); Gson gson = new GsonBuilder() .registerTypeAdapterFactory(rta) .create(); CreditCard original = new CreditCard("Jesse", 234); assertEquals("{\"type\":\"CreditCard\",\"cvv\":234,\"ownerName\":\"Jesse\"}", gson.toJson(original, BillingInstrument.class)); BillingInstrument deserialized = gson.fromJson( "{type:'CreditCard',cvv:234,ownerName:'Jesse'}", BillingInstrument.class); assertEquals("Jesse", deserialized.ownerName); assertTrue(deserialized instanceof CreditCard); } public void testRuntimeTypeIsBaseType() { TypeAdapterFactory rta = RuntimeTypeAdapterFactory.of( BillingInstrument.class) .registerSubtype(BillingInstrument.class); Gson gson = new GsonBuilder() .registerTypeAdapterFactory(rta) .create(); BillingInstrument original = new BillingInstrument("Jesse"); assertEquals("{\"type\":\"BillingInstrument\",\"ownerName\":\"Jesse\"}", gson.toJson(original, BillingInstrument.class)); BillingInstrument deserialized = gson.fromJson( "{type:'BillingInstrument',ownerName:'Jesse'}", BillingInstrument.class); assertEquals("Jesse", deserialized.ownerName); } public void testNullBaseType() { try { RuntimeTypeAdapterFactory.of(null); fail(); } catch (NullPointerException expected) { } } public void testNullTypeFieldName() { try { RuntimeTypeAdapterFactory.of(BillingInstrument.class, null); fail(); } catch (NullPointerException expected) { } } public void testNullSubtype() { RuntimeTypeAdapterFactory rta = RuntimeTypeAdapterFactory.of( BillingInstrument.class); try { rta.registerSubtype(null); fail(); } catch (NullPointerException expected) { } } public void testNullLabel() { RuntimeTypeAdapterFactory rta = RuntimeTypeAdapterFactory.of( BillingInstrument.class); try { rta.registerSubtype(CreditCard.class, null); fail(); } catch (NullPointerException expected) { } } public void testDuplicateSubtype() { RuntimeTypeAdapterFactory rta = RuntimeTypeAdapterFactory.of( BillingInstrument.class); rta.registerSubtype(CreditCard.class, "CC"); try { rta.registerSubtype(CreditCard.class, "Visa"); fail(); } catch (IllegalArgumentException expected) { } } public void testDuplicateLabel() { RuntimeTypeAdapterFactory rta = RuntimeTypeAdapterFactory.of( BillingInstrument.class); rta.registerSubtype(CreditCard.class, "CC"); try { rta.registerSubtype(BankTransfer.class, "CC"); fail(); } catch (IllegalArgumentException expected) { } } public void testDeserializeMissingTypeField() { TypeAdapterFactory billingAdapter = RuntimeTypeAdapterFactory.of(BillingInstrument.class) .registerSubtype(CreditCard.class); Gson gson = new GsonBuilder() .registerTypeAdapterFactory(billingAdapter) .create(); try { gson.fromJson("{ownerName:'Jesse'}", BillingInstrument.class); fail(); } catch (JsonParseException expected) { } } public void testDeserializeMissingSubtype() { TypeAdapterFactory billingAdapter = RuntimeTypeAdapterFactory.of(BillingInstrument.class) .registerSubtype(BankTransfer.class); Gson gson = new GsonBuilder() .registerTypeAdapterFactory(billingAdapter) .create(); try { gson.fromJson("{type:'CreditCard',ownerName:'Jesse'}", BillingInstrument.class); fail(); } catch (JsonParseException expected) { } } public void testSerializeMissingSubtype() { TypeAdapterFactory billingAdapter = RuntimeTypeAdapterFactory.of(BillingInstrument.class) .registerSubtype(BankTransfer.class); Gson gson = new GsonBuilder() .registerTypeAdapterFactory(billingAdapter) .create(); try { gson.toJson(new CreditCard("Jesse", 456), BillingInstrument.class); fail(); } catch (JsonParseException expected) { } } public void testSerializeCollidingTypeFieldName() { TypeAdapterFactory billingAdapter = RuntimeTypeAdapterFactory.of(BillingInstrument.class, "cvv") .registerSubtype(CreditCard.class); Gson gson = new GsonBuilder() .registerTypeAdapterFactory(billingAdapter) .create(); try { gson.toJson(new CreditCard("Jesse", 456), BillingInstrument.class); fail(); } catch (JsonParseException expected) { } } public void testSerializeWrappedNullValue() { TypeAdapterFactory billingAdapter = RuntimeTypeAdapterFactory.of(BillingInstrument.class) .registerSubtype(CreditCard.class) .registerSubtype(BankTransfer.class); Gson gson = new GsonBuilder() .registerTypeAdapterFactory(billingAdapter) .create(); String serialized = gson.toJson(new BillingInstrumentWrapper(null), BillingInstrumentWrapper.class); BillingInstrumentWrapper deserialized = gson.fromJson(serialized, BillingInstrumentWrapper.class); assertNull(deserialized.instrument); } static class BillingInstrumentWrapper { BillingInstrument instrument; BillingInstrumentWrapper(BillingInstrument instrument) { this.instrument = instrument; } } static class BillingInstrument { private final String ownerName; BillingInstrument(String ownerName) { this.ownerName = ownerName; } } static class CreditCard extends BillingInstrument { int cvv; CreditCard(String ownerName, int cvv) { super(ownerName); this.cvv = cvv; } } static class BankTransfer extends BillingInstrument { int bankAccount; BankTransfer(String ownerName, int bankAccount) { super(ownerName); this.bankAccount = bankAccount; } } } gson-gson-parent-2.8.2/extras/src/test/java/com/google/gson/typeadapters/UtcDateTypeAdapterTest.java000066400000000000000000000060551316034351600336350ustar00rootroot00000000000000/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.typeadapters; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import com.google.gson.JsonParseException; import junit.framework.TestCase; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public final class UtcDateTypeAdapterTest extends TestCase { private final Gson gson = new GsonBuilder() .registerTypeAdapter(Date.class, new UtcDateTypeAdapter()) .create(); public void testLocalTimeZone() { Date expected = new Date(); String json = gson.toJson(expected); Date actual = gson.fromJson(json, Date.class); assertEquals(expected.getTime(), actual.getTime()); } public void testDifferentTimeZones() { for (String timeZone : TimeZone.getAvailableIDs()) { Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(timeZone)); Date expected = cal.getTime(); String json = gson.toJson(expected); // System.out.println(json + ": " + timeZone); Date actual = gson.fromJson(json, Date.class); assertEquals(expected.getTime(), actual.getTime()); } } /** * JDK 1.7 introduced support for XXX format to indicate UTC date. But Android is older JDK. * We want to make sure that this date is parseable in Android. */ public void testUtcDatesOnJdkBefore1_7() { Gson gson = new GsonBuilder() .registerTypeAdapter(Date.class, new UtcDateTypeAdapter()) .create(); gson.fromJson("'2014-12-05T04:00:00.000Z'", Date.class); } public void testUtcWithJdk7Default() { Date expected = new Date(); SimpleDateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.US); iso8601Format.setTimeZone(TimeZone.getTimeZone("UTC")); String expectedJson = "\"" + iso8601Format.format(expected) + "\""; String actualJson = gson.toJson(expected); assertEquals(expectedJson, actualJson); Date actual = gson.fromJson(expectedJson, Date.class); assertEquals(expected.getTime(), actual.getTime()); } public void testNullDateSerialization() { String json = gson.toJson(null, Date.class); assertEquals("null", json); } public void testWellFormedParseException() { try { gson.fromJson("2017-06-20T14:32:30", Date.class); fail("No exception"); } catch (JsonParseException exe) { assertEquals(exe.getMessage(), "java.text.ParseException: Failed to parse date ['2017-06-20T14']: 2017-06-20T14"); } } } gson-gson-parent-2.8.2/gson/000077500000000000000000000000001316034351600156745ustar00rootroot00000000000000gson-gson-parent-2.8.2/gson/Gson 2.1 notes.txt000066400000000000000000000004541316034351600207400ustar00rootroot00000000000000Dropped support for GsonBuilder.registerTypeHierarchyAdapter+InstanceCreator Relax registerTypeHierarchyAdapter order Gson 2.0 failed if you registered Manager then Employee would fail Gson 2.1 it isn't a problem com.google.gson.functional.TypeHierarchyAdapterTest#testRegisterSubTypeFirstNotAllowedgson-gson-parent-2.8.2/gson/LICENSE000066400000000000000000000264521316034351600167120ustar00rootroot00000000000000Google Gson Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2008-2011 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. gson-gson-parent-2.8.2/gson/README000066400000000000000000000005731316034351600165610ustar00rootroot00000000000000Gson is a Java library that can be used to convert a Java object into its JSON representation. It can also be used to convert a JSON string into an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of. Complete Gson documentation is available at its project page https://github.com/google/gson gson-gson-parent-2.8.2/gson/assembly-descriptor.xml000066400000000000000000000007051316034351600224130ustar00rootroot00000000000000 release zip README* LICENSE* target gson-*.jar gson-gson-parent-2.8.2/gson/bnd.bnd000066400000000000000000000006641316034351600171320ustar00rootroot00000000000000Bundle-SymbolicName: com.google.gson Bundle-Name: ${project.name} Bundle-Description: ${project.description} Bundle-Vendor: Google Gson Project Bundle-ContactAddress: ${project.parent.url} Bundle-RequiredExecutionEnvironment: J2SE-1.5, JavaSE-1.6, JavaSE-1.7, JavaSE-1.8 -removeheaders: Private-Package -exportcontents:\ com.google.gson,\ com.google.gson.annotations,\ com.google.gson.reflect,\ com.google.gson.stream gson-gson-parent-2.8.2/gson/docs/000077500000000000000000000000001316034351600166245ustar00rootroot00000000000000gson-gson-parent-2.8.2/gson/docs/javadocs/000077500000000000000000000000001316034351600204165ustar00rootroot00000000000000gson-gson-parent-2.8.2/gson/docs/javadocs/allclasses-frame.html000066400000000000000000000120201316034351600245150ustar00rootroot00000000000000 All Classes (Gson 2.3.1 API) All Classes
ExclusionStrategy
Expose
FieldAttributes
FieldNamingPolicy
FieldNamingStrategy
Gson
GsonBuilder
InstanceCreator
JsonAdapter
JsonArray
JsonDeserializationContext
JsonDeserializer
JsonElement
JsonIOException
JsonNull
JsonObject
JsonParseException
JsonParser
JsonPrimitive
JsonReader
JsonSerializationContext
JsonSerializer
JsonStreamParser
JsonSyntaxException
JsonToken
JsonWriter
LongSerializationPolicy
MalformedJsonException
SerializedName
Since
TypeAdapter
TypeAdapterFactory
TypeToken
Until
gson-gson-parent-2.8.2/gson/docs/javadocs/allclasses-noframe.html000066400000000000000000000105501316034351600250600ustar00rootroot00000000000000 All Classes (Gson 2.3.1 API) All Classes
ExclusionStrategy
Expose
FieldAttributes
FieldNamingPolicy
FieldNamingStrategy
Gson
GsonBuilder
InstanceCreator
JsonAdapter
JsonArray
JsonDeserializationContext
JsonDeserializer
JsonElement
JsonIOException
JsonNull
JsonObject
JsonParseException
JsonParser
JsonPrimitive
JsonReader
JsonSerializationContext
JsonSerializer
JsonStreamParser
JsonSyntaxException
JsonToken
JsonWriter
LongSerializationPolicy
MalformedJsonException
SerializedName
Since
TypeAdapter
TypeAdapterFactory
TypeToken
Until
gson-gson-parent-2.8.2/gson/docs/javadocs/com/000077500000000000000000000000001316034351600211745ustar00rootroot00000000000000gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/000077500000000000000000000000001316034351600224505ustar00rootroot00000000000000gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/000077500000000000000000000000001316034351600234165ustar00rootroot00000000000000gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/ExclusionStrategy.html000066400000000000000000000316201316034351600300020ustar00rootroot00000000000000 ExclusionStrategy (Gson 2.3.1 API)

com.google.gson
Interface ExclusionStrategy


public interface ExclusionStrategy

A strategy (or policy) definition that is used to decide whether or not a field or top-level class should be serialized or deserialized as part of the JSON output/input. For serialization, if the shouldSkipClass(Class) method returns true then that class or field type will not be part of the JSON output. For deserialization, if shouldSkipClass(Class) returns true, then it will not be set as part of the Java object structure.

The following are a few examples that shows how you can use this exclusion mechanism.

Exclude fields and objects based on a particular class type:

 private static class SpecificClassExclusionStrategy implements ExclusionStrategy {
   private final Class<?> excludedThisClass;

   public SpecificClassExclusionStrategy(Class<?> excludedThisClass) {
     this.excludedThisClass = excludedThisClass;
   }

   public boolean shouldSkipClass(Class<?> clazz) {
     return excludedThisClass.equals(clazz);
   }

   public boolean shouldSkipField(FieldAttributes f) {
     return excludedThisClass.equals(f.getDeclaredClass());
   }
 }
 

Excludes fields and objects based on a particular annotation:

 public @interface FooAnnotation {
   // some implementation here
 }

 // Excludes any field (or class) that is tagged with an "@FooAnnotation"
 private static class FooAnnotationExclusionStrategy implements ExclusionStrategy {
   public boolean shouldSkipClass(Class<?> clazz) {
     return clazz.getAnnotation(FooAnnotation.class) != null;
   }

   public boolean shouldSkipField(FieldAttributes f) {
     return f.getAnnotation(FooAnnotation.class) != null;
   }
 }
 

Now if you want to configure Gson to use a user defined exclusion strategy, then the GsonBuilder is required. The following is an example of how you can use the GsonBuilder to configure Gson to use one of the above sample:

 ExclusionStrategy excludeStrings = new UserDefinedExclusionStrategy(String.class);
 Gson gson = new GsonBuilder()
     .setExclusionStrategies(excludeStrings)
     .create();
 

For certain model classes, you may only want to serialize a field, but exclude it for deserialization. To do that, you can write an ExclusionStrategy as per normal; however, you would register it with the GsonBuilder.addDeserializationExclusionStrategy(ExclusionStrategy) method. For example:

 ExclusionStrategy excludeStrings = new UserDefinedExclusionStrategy(String.class);
 Gson gson = new GsonBuilder()
     .addDeserializationExclusionStrategy(excludeStrings)
     .create();
 

Since:
1.4
Author:
Inderjeet Singh, Joel Leitch
See Also:
GsonBuilder.setExclusionStrategies(ExclusionStrategy...), GsonBuilder.addDeserializationExclusionStrategy(ExclusionStrategy), GsonBuilder.addSerializationExclusionStrategy(ExclusionStrategy)

Method Summary
 boolean shouldSkipClass(Class<?> clazz)
           
 boolean shouldSkipField(FieldAttributes f)
           
 

Method Detail

shouldSkipField

boolean shouldSkipField(FieldAttributes f)
Parameters:
f - the field object that is under test
Returns:
true if the field should be ignored; otherwise false

shouldSkipClass

boolean shouldSkipClass(Class<?> clazz)
Parameters:
clazz - the class object that is under test
Returns:
true if the class should be ignored; otherwise false


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/FieldAttributes.html000066400000000000000000000507771316034351600274160ustar00rootroot00000000000000 FieldAttributes (Gson 2.3.1 API)

com.google.gson
Class FieldAttributes

java.lang.Object
  extended by com.google.gson.FieldAttributes

public final class FieldAttributes
extends Object

A data object that stores attributes of a field.

This class is immutable; therefore, it can be safely shared across threads.

Since:
1.4
Author:
Inderjeet Singh, Joel Leitch

Constructor Summary
FieldAttributes(Field f)
          Constructs a Field Attributes object from the f.
 
Method Summary
<T extends Annotation>
T
getAnnotation(Class<T> annotation)
          Return the T annotation object from this field if it exist; otherwise returns null.
 Collection<Annotation> getAnnotations()
          Return the annotations that are present on this field.
 Class<?> getDeclaredClass()
          Returns the Class object that was declared for this field.
 Type getDeclaredType()
          For example, assume the following class definition:
 public class Foo {
   private String bar;
   private List<String> red;
 }

 Type listParmeterizedType = new TypeToken<List<String>>() {}.getType();
 Class<?> getDeclaringClass()
           
 String getName()
           
 boolean hasModifier(int modifier)
          Returns true if the field is defined with the modifier.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

FieldAttributes

public FieldAttributes(Field f)
Constructs a Field Attributes object from the f.

Parameters:
f - the field to pull attributes from
Method Detail

getDeclaringClass

public Class<?> getDeclaringClass()
Returns:
the declaring class that contains this field

getName

public String getName()
Returns:
the name of the field

getDeclaredType

public Type getDeclaredType()

For example, assume the following class definition:

 public class Foo {
   private String bar;
   private List<String> red;
 }

 Type listParmeterizedType = new TypeToken<List<String>>() {}.getType();
 

This method would return String.class for the bar field and listParameterizedType for the red field.

Returns:
the specific type declared for this field

getDeclaredClass

public Class<?> getDeclaredClass()
Returns the Class object that was declared for this field.

For example, assume the following class definition:

 public class Foo {
   private String bar;
   private List<String> red;
 }
 

This method would return String.class for the bar field and List.class for the red field.

Returns:
the specific class object that was declared for the field

getAnnotation

public <T extends Annotation> T getAnnotation(Class<T> annotation)
Return the T annotation object from this field if it exist; otherwise returns null.

Parameters:
annotation - the class of the annotation that will be retrieved
Returns:
the annotation instance if it is bound to the field; otherwise null

getAnnotations

public Collection<Annotation> getAnnotations()
Return the annotations that are present on this field.

Returns:
an array of all the annotations set on the field
Since:
1.4

hasModifier

public boolean hasModifier(int modifier)
Returns true if the field is defined with the modifier.

This method is meant to be called as:

 boolean hasPublicModifier = fieldAttribute.hasModifier(java.lang.reflect.Modifier.PUBLIC);
 

See Also:
Modifier


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/FieldNamingPolicy.html000066400000000000000000000556051316034351600276540ustar00rootroot00000000000000 FieldNamingPolicy (Gson 2.3.1 API)

com.google.gson
Enum FieldNamingPolicy

java.lang.Object
  extended by java.lang.Enum<FieldNamingPolicy>
      extended by com.google.gson.FieldNamingPolicy
All Implemented Interfaces:
FieldNamingStrategy, Serializable, Comparable<FieldNamingPolicy>

public enum FieldNamingPolicy
extends Enum<FieldNamingPolicy>
implements FieldNamingStrategy

An enumeration that defines a few standard naming conventions for JSON field names. This enumeration should be used in conjunction with GsonBuilder to configure a Gson instance to properly translate Java field names into the desired JSON field names.

Author:
Inderjeet Singh, Joel Leitch

Enum Constant Summary
IDENTITY
          Using this naming policy with Gson will ensure that the field name is unchanged.
LOWER_CASE_WITH_DASHES
          Using this naming policy with Gson will modify the Java Field name from its camel cased form to a lower case field name where each word is separated by a dash (-).
LOWER_CASE_WITH_UNDERSCORES
          Using this naming policy with Gson will modify the Java Field name from its camel cased form to a lower case field name where each word is separated by an underscore (_).
UPPER_CAMEL_CASE
          Using this naming policy with Gson will ensure that the first "letter" of the Java field name is capitalized when serialized to its JSON form.
UPPER_CAMEL_CASE_WITH_SPACES
          Using this naming policy with Gson will ensure that the first "letter" of the Java field name is capitalized when serialized to its JSON form and the words will be separated by a space.
 
Method Summary
static FieldNamingPolicy valueOf(String name)
          Returns the enum constant of this type with the specified name.
static FieldNamingPolicy[] values()
          Returns an array containing the constants of this enum type, in the order they are declared.
 
Methods inherited from class java.lang.Enum
clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf
 
Methods inherited from class java.lang.Object
getClass, notify, notifyAll, wait, wait, wait
 
Methods inherited from interface com.google.gson.FieldNamingStrategy
translateName
 

Enum Constant Detail

IDENTITY

public static final FieldNamingPolicy IDENTITY
Using this naming policy with Gson will ensure that the field name is unchanged.


UPPER_CAMEL_CASE

public static final FieldNamingPolicy UPPER_CAMEL_CASE
Using this naming policy with Gson will ensure that the first "letter" of the Java field name is capitalized when serialized to its JSON form.

Here's a few examples of the form "Java Field Name" ---> "JSON Field Name":

  • someFieldName ---> SomeFieldName
  • _someFieldName ---> _SomeFieldName


UPPER_CAMEL_CASE_WITH_SPACES

public static final FieldNamingPolicy UPPER_CAMEL_CASE_WITH_SPACES
Using this naming policy with Gson will ensure that the first "letter" of the Java field name is capitalized when serialized to its JSON form and the words will be separated by a space.

Here's a few examples of the form "Java Field Name" ---> "JSON Field Name":

  • someFieldName ---> Some Field Name
  • _someFieldName ---> _Some Field Name

Since:
1.4

LOWER_CASE_WITH_UNDERSCORES

public static final FieldNamingPolicy LOWER_CASE_WITH_UNDERSCORES
Using this naming policy with Gson will modify the Java Field name from its camel cased form to a lower case field name where each word is separated by an underscore (_).

Here's a few examples of the form "Java Field Name" ---> "JSON Field Name":

  • someFieldName ---> some_field_name
  • _someFieldName ---> _some_field_name
  • aStringField ---> a_string_field
  • aURL ---> a_u_r_l


LOWER_CASE_WITH_DASHES

public static final FieldNamingPolicy LOWER_CASE_WITH_DASHES
Using this naming policy with Gson will modify the Java Field name from its camel cased form to a lower case field name where each word is separated by a dash (-).

Here's a few examples of the form "Java Field Name" ---> "JSON Field Name":

  • someFieldName ---> some-field-name
  • _someFieldName ---> _some-field-name
  • aStringField ---> a-string-field
  • aURL ---> a-u-r-l
Using dashes in JavaScript is not recommended since dash is also used for a minus sign in expressions. This requires that a field named with dashes is always accessed as a quoted property like myobject['my-field']. Accessing it as an object field myobject.my-field will result in an unintended javascript expression.

Since:
1.4
Method Detail

values

public static FieldNamingPolicy[] values()
Returns an array containing the constants of this enum type, in the order they are declared. This method may be used to iterate over the constants as follows:
for (FieldNamingPolicy c : FieldNamingPolicy.values())
    System.out.println(c);

Returns:
an array containing the constants of this enum type, in the order they are declared

valueOf

public static FieldNamingPolicy valueOf(String name)
Returns the enum constant of this type with the specified name. The string must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)

Parameters:
name - the name of the enum constant to be returned.
Returns:
the enum constant with the specified name
Throws:
IllegalArgumentException - if this enum type has no constant with the specified name
NullPointerException - if the argument is null


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/FieldNamingStrategy.html000066400000000000000000000226331316034351600302120ustar00rootroot00000000000000 FieldNamingStrategy (Gson 2.3.1 API)

com.google.gson
Interface FieldNamingStrategy

All Known Implementing Classes:
FieldNamingPolicy

public interface FieldNamingStrategy

A mechanism for providing custom field naming in Gson. This allows the client code to translate field names into a particular convention that is not supported as a normal Java field declaration rules. For example, Java does not support "-" characters in a field name.

Since:
1.3
Author:
Inderjeet Singh, Joel Leitch

Method Summary
 String translateName(Field f)
          Translates the field name into its JSON field name representation.
 

Method Detail

translateName

String translateName(Field f)
Translates the field name into its JSON field name representation.

Parameters:
f - the field object that we are translating
Returns:
the translated field name.
Since:
1.3


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/Gson.html000066400000000000000000002160301316034351600252140ustar00rootroot00000000000000 Gson (Gson 2.3.1 API)

com.google.gson
Class Gson

java.lang.Object
  extended by com.google.gson.Gson

public final class Gson
extends Object

This is the main class for using Gson. Gson is typically used by first constructing a Gson instance and then invoking toJson(Object) or fromJson(String, Class) methods on it.

You can create a Gson instance by invoking new Gson() if the default configuration is all you need. You can also use GsonBuilder to build a Gson instance with various configuration options such as versioning support, pretty printing, custom JsonSerializers, JsonDeserializers, and InstanceCreators.

Here is an example of how Gson is used for a simple Class:

 Gson gson = new Gson(); // Or use new GsonBuilder().create();
 MyType target = new MyType();
 String json = gson.toJson(target); // serializes target to Json
 MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2
 

If the object that your are serializing/deserializing is a ParameterizedType (i.e. contains at least one type parameter and may be an array) then you must use the toJson(Object, Type) or fromJson(String, Type) method. Here is an example for serializing and deserialing a ParameterizedType:

 Type listType = new TypeToken<List<String>>() {}.getType();
 List<String> target = new LinkedList<String>();
 target.add("blah");

 Gson gson = new Gson();
 String json = gson.toJson(target, listType);
 List<String> target2 = gson.fromJson(json, listType);
 

See the Gson User Guide for a more complete set of examples.

Author:
Inderjeet Singh, Joel Leitch, Jesse Wilson
See Also:
TypeToken

Constructor Summary
Gson()
          Constructs a Gson object with default configuration.
 
Method Summary
<T> T
fromJson(JsonElement json, Class<T> classOfT)
          This method deserializes the Json read from the specified parse tree into an object of the specified type.
<T> T
fromJson(JsonElement json, Type typeOfT)
          This method deserializes the Json read from the specified parse tree into an object of the specified type.
<T> T
fromJson(JsonReader reader, Type typeOfT)
          Reads the next JSON value from reader and convert it to an object of type typeOfT.
<T> T
fromJson(Reader json, Class<T> classOfT)
          This method deserializes the Json read from the specified reader into an object of the specified class.
<T> T
fromJson(Reader json, Type typeOfT)
          This method deserializes the Json read from the specified reader into an object of the specified type.
<T> T
fromJson(String json, Class<T> classOfT)
          This method deserializes the specified Json into an object of the specified class.
<T> T
fromJson(String json, Type typeOfT)
          This method deserializes the specified Json into an object of the specified type.
<T> TypeAdapter<T>
getAdapter(Class<T> type)
          Returns the type adapter for type.
<T> TypeAdapter<T>
getAdapter(TypeToken<T> type)
          Returns the type adapter for type.
<T> TypeAdapter<T>
getDelegateAdapter(TypeAdapterFactory skipPast, TypeToken<T> type)
          This method is used to get an alternate type adapter for the specified type.
 String toJson(JsonElement jsonElement)
          Converts a tree of JsonElements into its equivalent JSON representation.
 void toJson(JsonElement jsonElement, Appendable writer)
          Writes out the equivalent JSON for a tree of JsonElements.
 void toJson(JsonElement jsonElement, JsonWriter writer)
          Writes the JSON for jsonElement to writer.
 String toJson(Object src)
          This method serializes the specified object into its equivalent Json representation.
 void toJson(Object src, Appendable writer)
          This method serializes the specified object into its equivalent Json representation.
 String toJson(Object src, Type typeOfSrc)
          This method serializes the specified object, including those of generic types, into its equivalent Json representation.
 void toJson(Object src, Type typeOfSrc, Appendable writer)
          This method serializes the specified object, including those of generic types, into its equivalent Json representation.
 void toJson(Object src, Type typeOfSrc, JsonWriter writer)
          Writes the JSON representation of src of type typeOfSrc to writer.
 JsonElement toJsonTree(Object src)
          This method serializes the specified object into its equivalent representation as a tree of JsonElements.
 JsonElement toJsonTree(Object src, Type typeOfSrc)
          This method serializes the specified object, including those of generic types, into its equivalent representation as a tree of JsonElements.
 String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

Gson

public Gson()
Constructs a Gson object with default configuration. The default configuration has the following settings:

Method Detail

getAdapter

public <T> TypeAdapter<T> getAdapter(TypeToken<T> type)
Returns the type adapter for type.

Throws:
IllegalArgumentException - if this GSON cannot serialize and deserialize type.

getDelegateAdapter

public <T> TypeAdapter<T> getDelegateAdapter(TypeAdapterFactory skipPast,
                                             TypeToken<T> type)
This method is used to get an alternate type adapter for the specified type. This is used to access a type adapter that is overridden by a TypeAdapterFactory that you may have registered. This features is typically used when you want to register a type adapter that does a little bit of work but then delegates further processing to the Gson default type adapter. Here is an example:

Let's say we want to write a type adapter that counts the number of objects being read from or written to JSON. We can achieve this by writing a type adapter factory that uses the getDelegateAdapter method:

 class StatsTypeAdapterFactory implements TypeAdapterFactory {
    public int numReads = 0;
    public int numWrites = 0;
    public &lt;T&gt; TypeAdapter&lt;T&gt; create(Gson gson, TypeToken&lt;T&gt; type) {
      final TypeAdapter&lt;T&gt; delegate = gson.getDelegateAdapter(this, type);
      return new TypeAdapter&lt;T&gt;() {
        public void write(JsonWriter out, T value) throws IOException {
          ++numWrites;
          delegate.write(out, value);
        }
        public T read(JsonReader in) throws IOException {
          ++numReads;
          return delegate.read(in);
        }
      };
    }
  }
   
This factory can now be used like this:
 StatsTypeAdapterFactory stats = new StatsTypeAdapterFactory();
  Gson gson = new GsonBuilder().registerTypeAdapterFactory(stats).create();
  // Call gson.toJson() and fromJson methods on objects
  System.out.println("Num JSON reads" + stats.numReads);
  System.out.println("Num JSON writes" + stats.numWrites);
  
Note that since you can not override type adapter factories for String and Java primitive types, our stats factory will not count the number of String or primitives that will be read or written.

Parameters:
skipPast - The type adapter factory that needs to be skipped while searching for a matching type adapter. In most cases, you should just pass this (the type adapter factory from where getDelegateAdapter(com.google.gson.TypeAdapterFactory, com.google.gson.reflect.TypeToken) method is being invoked).
type - Type for which the delegate adapter is being searched for.
Since:
2.2

getAdapter

public <T> TypeAdapter<T> getAdapter(Class<T> type)
Returns the type adapter for type.

Throws:
IllegalArgumentException - if this GSON cannot serialize and deserialize type.

toJsonTree

public JsonElement toJsonTree(Object src)
This method serializes the specified object into its equivalent representation as a tree of JsonElements. This method should be used when the specified object is not a generic type. This method uses Object.getClass() to get the type for the specified object, but the getClass() loses the generic type information because of the Type Erasure feature of Java. Note that this method works fine if the any of the object fields are of generic type, just the object itself should not be of a generic type. If the object is of generic type, use toJsonTree(Object, Type) instead.

Parameters:
src - the object for which Json representation is to be created setting for Gson
Returns:
Json representation of src.
Since:
1.4

toJsonTree

public JsonElement toJsonTree(Object src,
                              Type typeOfSrc)
This method serializes the specified object, including those of generic types, into its equivalent representation as a tree of JsonElements. This method must be used if the specified object is a generic type. For non-generic objects, use toJsonTree(Object) instead.

Parameters:
src - the object for which JSON representation is to be created
typeOfSrc - The specific genericized type of src. You can obtain this type by using the TypeToken class. For example, to get the type for Collection<Foo>, you should use:
 Type typeOfSrc = new TypeToken<Collection<Foo>>(){}.getType();
 
Returns:
Json representation of src
Since:
1.4

toJson

public String toJson(Object src)
This method serializes the specified object into its equivalent Json representation. This method should be used when the specified object is not a generic type. This method uses Object.getClass() to get the type for the specified object, but the getClass() loses the generic type information because of the Type Erasure feature of Java. Note that this method works fine if the any of the object fields are of generic type, just the object itself should not be of a generic type. If the object is of generic type, use toJson(Object, Type) instead. If you want to write out the object to a Writer, use toJson(Object, Appendable) instead.

Parameters:
src - the object for which Json representation is to be created setting for Gson
Returns:
Json representation of src.

toJson

public String toJson(Object src,
                     Type typeOfSrc)
This method serializes the specified object, including those of generic types, into its equivalent Json representation. This method must be used if the specified object is a generic type. For non-generic objects, use toJson(Object) instead. If you want to write out the object to a Appendable, use toJson(Object, Type, Appendable) instead.

Parameters:
src - the object for which JSON representation is to be created
typeOfSrc - The specific genericized type of src. You can obtain this type by using the TypeToken class. For example, to get the type for Collection<Foo>, you should use:
 Type typeOfSrc = new TypeToken<Collection<Foo>>(){}.getType();
 
Returns:
Json representation of src

toJson

public void toJson(Object src,
                   Appendable writer)
            throws JsonIOException
This method serializes the specified object into its equivalent Json representation. This method should be used when the specified object is not a generic type. This method uses Object.getClass() to get the type for the specified object, but the getClass() loses the generic type information because of the Type Erasure feature of Java. Note that this method works fine if the any of the object fields are of generic type, just the object itself should not be of a generic type. If the object is of generic type, use toJson(Object, Type, Appendable) instead.

Parameters:
src - the object for which Json representation is to be created setting for Gson
writer - Writer to which the Json representation needs to be written
Throws:
JsonIOException - if there was a problem writing to the writer
Since:
1.2

toJson

public void toJson(Object src,
                   Type typeOfSrc,
                   Appendable writer)
            throws JsonIOException
This method serializes the specified object, including those of generic types, into its equivalent Json representation. This method must be used if the specified object is a generic type. For non-generic objects, use toJson(Object, Appendable) instead.

Parameters:
src - the object for which JSON representation is to be created
typeOfSrc - The specific genericized type of src. You can obtain this type by using the TypeToken class. For example, to get the type for Collection<Foo>, you should use:
 Type typeOfSrc = new TypeToken<Collection<Foo>>(){}.getType();
 
writer - Writer to which the Json representation of src needs to be written.
Throws:
JsonIOException - if there was a problem writing to the writer
Since:
1.2

toJson

public void toJson(Object src,
                   Type typeOfSrc,
                   JsonWriter writer)
            throws JsonIOException
Writes the JSON representation of src of type typeOfSrc to writer.

Throws:
JsonIOException - if there was a problem writing to the writer

toJson

public String toJson(JsonElement jsonElement)
Converts a tree of JsonElements into its equivalent JSON representation.

Parameters:
jsonElement - root of a tree of JsonElements
Returns:
JSON String representation of the tree
Since:
1.4

toJson

public void toJson(JsonElement jsonElement,
                   Appendable writer)
            throws JsonIOException
Writes out the equivalent JSON for a tree of JsonElements.

Parameters:
jsonElement - root of a tree of JsonElements
writer - Writer to which the Json representation needs to be written
Throws:
JsonIOException - if there was a problem writing to the writer
Since:
1.4

toJson

public void toJson(JsonElement jsonElement,
                   JsonWriter writer)
            throws JsonIOException
Writes the JSON for jsonElement to writer.

Throws:
JsonIOException - if there was a problem writing to the writer

fromJson

public <T> T fromJson(String json,
                      Class<T> classOfT)
           throws JsonSyntaxException
This method deserializes the specified Json into an object of the specified class. It is not suitable to use if the specified class is a generic type since it will not have the generic type information because of the Type Erasure feature of Java. Therefore, this method should not be used if the desired type is a generic type. Note that this method works fine if the any of the fields of the specified object are generics, just the object itself should not be a generic type. For the cases when the object is of generic type, invoke fromJson(String, Type). If you have the Json in a Reader instead of a String, use fromJson(Reader, Class) instead.

Type Parameters:
T - the type of the desired object
Parameters:
json - the string from which the object is to be deserialized
classOfT - the class of T
Returns:
an object of type T from the string. Returns null if json is null.
Throws:
JsonSyntaxException - if json is not a valid representation for an object of type classOfT

fromJson

public <T> T fromJson(String json,
                      Type typeOfT)
           throws JsonSyntaxException
This method deserializes the specified Json into an object of the specified type. This method is useful if the specified object is a generic type. For non-generic objects, use fromJson(String, Class) instead. If you have the Json in a Reader instead of a String, use fromJson(Reader, Type) instead.

Type Parameters:
T - the type of the desired object
Parameters:
json - the string from which the object is to be deserialized
typeOfT - The specific genericized type of src. You can obtain this type by using the TypeToken class. For example, to get the type for Collection<Foo>, you should use:
 Type typeOfT = new TypeToken<Collection<Foo>>(){}.getType();
 
Returns:
an object of type T from the string. Returns null if json is null.
Throws:
JsonParseException - if json is not a valid representation for an object of type typeOfT
JsonSyntaxException - if json is not a valid representation for an object of type

fromJson

public <T> T fromJson(Reader json,
                      Class<T> classOfT)
           throws JsonSyntaxException,
                  JsonIOException
This method deserializes the Json read from the specified reader into an object of the specified class. It is not suitable to use if the specified class is a generic type since it will not have the generic type information because of the Type Erasure feature of Java. Therefore, this method should not be used if the desired type is a generic type. Note that this method works fine if the any of the fields of the specified object are generics, just the object itself should not be a generic type. For the cases when the object is of generic type, invoke fromJson(Reader, Type). If you have the Json in a String form instead of a Reader, use fromJson(String, Class) instead.

Type Parameters:
T - the type of the desired object
Parameters:
json - the reader producing the Json from which the object is to be deserialized.
classOfT - the class of T
Returns:
an object of type T from the string. Returns null if json is at EOF.
Throws:
JsonIOException - if there was a problem reading from the Reader
JsonSyntaxException - if json is not a valid representation for an object of type
Since:
1.2

fromJson

public <T> T fromJson(Reader json,
                      Type typeOfT)
           throws JsonIOException,
                  JsonSyntaxException
This method deserializes the Json read from the specified reader into an object of the specified type. This method is useful if the specified object is a generic type. For non-generic objects, use fromJson(Reader, Class) instead. If you have the Json in a String form instead of a Reader, use fromJson(String, Type) instead.

Type Parameters:
T - the type of the desired object
Parameters:
json - the reader producing Json from which the object is to be deserialized
typeOfT - The specific genericized type of src. You can obtain this type by using the TypeToken class. For example, to get the type for Collection<Foo>, you should use:
 Type typeOfT = new TypeToken<Collection<Foo>>(){}.getType();
 
Returns:
an object of type T from the json. Returns null if json is at EOF.
Throws:
JsonIOException - if there was a problem reading from the Reader
JsonSyntaxException - if json is not a valid representation for an object of type
Since:
1.2

fromJson

public <T> T fromJson(JsonReader reader,
                      Type typeOfT)
           throws JsonIOException,
                  JsonSyntaxException
Reads the next JSON value from reader and convert it to an object of type typeOfT. Returns null, if the reader is at EOF. Since Type is not parameterized by T, this method is type unsafe and should be used carefully

Throws:
JsonIOException - if there was a problem writing to the Reader
JsonSyntaxException - if json is not a valid representation for an object of type

fromJson

public <T> T fromJson(JsonElement json,
                      Class<T> classOfT)
           throws JsonSyntaxException
This method deserializes the Json read from the specified parse tree into an object of the specified type. It is not suitable to use if the specified class is a generic type since it will not have the generic type information because of the Type Erasure feature of Java. Therefore, this method should not be used if the desired type is a generic type. Note that this method works fine if the any of the fields of the specified object are generics, just the object itself should not be a generic type. For the cases when the object is of generic type, invoke fromJson(JsonElement, Type).

Type Parameters:
T - the type of the desired object
Parameters:
json - the root of the parse tree of JsonElements from which the object is to be deserialized
classOfT - The class of T
Returns:
an object of type T from the json. Returns null if json is null.
Throws:
JsonSyntaxException - if json is not a valid representation for an object of type typeOfT
Since:
1.3

fromJson

public <T> T fromJson(JsonElement json,
                      Type typeOfT)
           throws JsonSyntaxException
This method deserializes the Json read from the specified parse tree into an object of the specified type. This method is useful if the specified object is a generic type. For non-generic objects, use fromJson(JsonElement, Class) instead.

Type Parameters:
T - the type of the desired object
Parameters:
json - the root of the parse tree of JsonElements from which the object is to be deserialized
typeOfT - The specific genericized type of src. You can obtain this type by using the TypeToken class. For example, to get the type for Collection<Foo>, you should use:
 Type typeOfT = new TypeToken<Collection<Foo>>(){}.getType();
 
Returns:
an object of type T from the json. Returns null if json is null.
Throws:
JsonSyntaxException - if json is not a valid representation for an object of type typeOfT
Since:
1.3

toString

public String toString()
Overrides:
toString in class Object


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/GsonBuilder.html000066400000000000000000001542321316034351600265300ustar00rootroot00000000000000 GsonBuilder (Gson 2.3.1 API)

com.google.gson
Class GsonBuilder

java.lang.Object
  extended by com.google.gson.GsonBuilder

public final class GsonBuilder
extends Object

Use this builder to construct a Gson instance when you need to set configuration options other than the default. For Gson with default configuration, it is simpler to use new Gson(). GsonBuilder is best used by creating it, and then invoking its various configuration methods, and finally calling create.

The following is an example shows how to use the GsonBuilder to construct a Gson instance:

 Gson gson = new GsonBuilder()
     .registerTypeAdapter(Id.class, new IdTypeAdapter())
     .enableComplexMapKeySerialization()
     .serializeNulls()
     .setDateFormat(DateFormat.LONG)
     .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
     .setPrettyPrinting()
     .setVersion(1.0)
     .create();
 

NOTES:

  • the order of invocation of configuration methods does not matter.
  • The default serialization of Date and its subclasses in Gson does not contain time-zone information. So, if you are using date/time instances, use GsonBuilder and its setDateFormat methods.

Author:
Inderjeet Singh, Joel Leitch, Jesse Wilson

Constructor Summary
GsonBuilder()
          Creates a GsonBuilder instance that can be used to build Gson with various configuration settings.
 
Method Summary
 GsonBuilder addDeserializationExclusionStrategy(ExclusionStrategy strategy)
          Configures Gson to apply the passed in exclusion strategy during deserialization.
 GsonBuilder addSerializationExclusionStrategy(ExclusionStrategy strategy)
          Configures Gson to apply the passed in exclusion strategy during serialization.
 Gson create()
          Creates a Gson instance based on the current configuration.
 GsonBuilder disableHtmlEscaping()
          By default, Gson escapes HTML characters such as < > etc.
 GsonBuilder disableInnerClassSerialization()
          Configures Gson to exclude inner classes during serialization.
 GsonBuilder enableComplexMapKeySerialization()
          Enabling this feature will only change the serialized form if the map key is a complex type (i.e.
 GsonBuilder excludeFieldsWithModifiers(int... modifiers)
          Configures Gson to excludes all class fields that have the specified modifiers.
 GsonBuilder excludeFieldsWithoutExposeAnnotation()
          Configures Gson to exclude all fields from consideration for serialization or deserialization that do not have the Expose annotation.
 GsonBuilder generateNonExecutableJson()
          Makes the output JSON non-executable in Javascript by prefixing the generated JSON with some special text.
 GsonBuilder registerTypeAdapter(Type type, Object typeAdapter)
          Configures Gson for custom serialization or deserialization.
 GsonBuilder registerTypeAdapterFactory(TypeAdapterFactory factory)
          Register a factory for type adapters.
 GsonBuilder registerTypeHierarchyAdapter(Class<?> baseType, Object typeAdapter)
          Configures Gson for custom serialization or deserialization for an inheritance type hierarchy.
 GsonBuilder serializeNulls()
          Configure Gson to serialize null fields.
 GsonBuilder serializeSpecialFloatingPointValues()
          Section 2.4 of JSON specification disallows special double values (NaN, Infinity, -Infinity).
 GsonBuilder setDateFormat(int style)
          Configures Gson to to serialize Date objects according to the style value provided.
 GsonBuilder setDateFormat(int dateStyle, int timeStyle)
          Configures Gson to to serialize Date objects according to the style value provided.
 GsonBuilder setDateFormat(String pattern)
          Configures Gson to serialize Date objects according to the pattern provided.
 GsonBuilder setExclusionStrategies(ExclusionStrategy... strategies)
          Configures Gson to apply a set of exclusion strategies during both serialization and deserialization.
 GsonBuilder setFieldNamingPolicy(FieldNamingPolicy namingConvention)
          Configures Gson to apply a specific naming policy to an object's field during serialization and deserialization.
 GsonBuilder setFieldNamingStrategy(FieldNamingStrategy fieldNamingStrategy)
          Configures Gson to apply a specific naming policy strategy to an object's field during serialization and deserialization.
 GsonBuilder setLongSerializationPolicy(LongSerializationPolicy serializationPolicy)
          Configures Gson to apply a specific serialization policy for Long and long objects.
 GsonBuilder setPrettyPrinting()
          Configures Gson to output Json that fits in a page for pretty printing.
 GsonBuilder setVersion(double ignoreVersionsAfter)
          Configures Gson to enable versioning support.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

GsonBuilder

public GsonBuilder()
Creates a GsonBuilder instance that can be used to build Gson with various configuration settings. GsonBuilder follows the builder pattern, and it is typically used by first invoking various configuration methods to set desired options, and finally calling create().

Method Detail

setVersion

public GsonBuilder setVersion(double ignoreVersionsAfter)
Configures Gson to enable versioning support.

Parameters:
ignoreVersionsAfter - any field or type marked with a version higher than this value are ignored during serialization or deserialization.
Returns:
a reference to this GsonBuilder object to fulfill the "Builder" pattern

excludeFieldsWithModifiers

public GsonBuilder excludeFieldsWithModifiers(int... modifiers)
Configures Gson to excludes all class fields that have the specified modifiers. By default, Gson will exclude all fields marked transient or static. This method will override that behavior.

Parameters:
modifiers - the field modifiers. You must use the modifiers specified in the Modifier class. For example, Modifier.TRANSIENT, Modifier.STATIC.
Returns:
a reference to this GsonBuilder object to fulfill the "Builder" pattern

generateNonExecutableJson

public GsonBuilder generateNonExecutableJson()
Makes the output JSON non-executable in Javascript by prefixing the generated JSON with some special text. This prevents attacks from third-party sites through script sourcing. See Gson Issue 42 for details.

Returns:
a reference to this GsonBuilder object to fulfill the "Builder" pattern
Since:
1.3

excludeFieldsWithoutExposeAnnotation

public GsonBuilder excludeFieldsWithoutExposeAnnotation()
Configures Gson to exclude all fields from consideration for serialization or deserialization that do not have the Expose annotation.

Returns:
a reference to this GsonBuilder object to fulfill the "Builder" pattern

serializeNulls

public GsonBuilder serializeNulls()
Configure Gson to serialize null fields. By default, Gson omits all fields that are null during serialization.

Returns:
a reference to this GsonBuilder object to fulfill the "Builder" pattern
Since:
1.2

enableComplexMapKeySerialization

public GsonBuilder enableComplexMapKeySerialization()
Enabling this feature will only change the serialized form if the map key is a complex type (i.e. non-primitive) in its serialized JSON form. The default implementation of map serialization uses toString() on the key; however, when this is called then one of the following cases apply:

Maps as JSON objects

For this case, assume that a type adapter is registered to serialize and deserialize some Point class, which contains an x and y coordinate, to/from the JSON Primitive string value "(x,y)". The Java map would then be serialized as a JsonObject.

Below is an example:

  Gson gson = new GsonBuilder()
       .register(Point.class, new MyPointTypeAdapter())
       .enableComplexMapKeySerialization()
       .create();

   Map<Point, String> original = new LinkedHashMap<Point, String>();
   original.put(new Point(5, 6), "a");
   original.put(new Point(8, 8), "b");
   System.out.println(gson.toJson(original, type));
 
The above code prints this JSON object:
  {
     "(5,6)": "a",
     "(8,8)": "b"
   }
 

Maps as JSON arrays

For this case, assume that a type adapter was NOT registered for some Point class, but rather the default Gson serialization is applied. In this case, some new Point(2,3) would serialize as {"x":2,"y":5}.

Given the assumption above, a Map<Point, String> will be serialize as an array of arrays (can be viewed as an entry set of pairs).

Below is an example of serializing complex types as JSON arrays:

 Gson gson = new GsonBuilder()
       .enableComplexMapKeySerialization()
       .create();

   Map<Point, String> original = new LinkedHashMap<Point, String>();
   original.put(new Point(5, 6), "a");
   original.put(new Point(8, 8), "b");
   System.out.println(gson.toJson(original, type));
 

 The JSON output would look as follows:
 
   [
     [
       {
         "x": 5,
         "y": 6
       },
       "a"
     ],
     [
       {
         "x": 8,
         "y": 8
       },
       "b"
     ]
   ]
 

Returns:
a reference to this GsonBuilder object to fulfill the "Builder" pattern
Since:
1.7

disableInnerClassSerialization

public GsonBuilder disableInnerClassSerialization()
Configures Gson to exclude inner classes during serialization.

Returns:
a reference to this GsonBuilder object to fulfill the "Builder" pattern
Since:
1.3

setLongSerializationPolicy

public GsonBuilder setLongSerializationPolicy(LongSerializationPolicy serializationPolicy)
Configures Gson to apply a specific serialization policy for Long and long objects.

Parameters:
serializationPolicy - the particular policy to use for serializing longs.
Returns:
a reference to this GsonBuilder object to fulfill the "Builder" pattern
Since:
1.3

setFieldNamingPolicy

public GsonBuilder setFieldNamingPolicy(FieldNamingPolicy namingConvention)
Configures Gson to apply a specific naming policy to an object's field during serialization and deserialization.

Parameters:
namingConvention - the JSON field naming convention to use for serialization and deserialization.
Returns:
a reference to this GsonBuilder object to fulfill the "Builder" pattern

setFieldNamingStrategy

public GsonBuilder setFieldNamingStrategy(FieldNamingStrategy fieldNamingStrategy)
Configures Gson to apply a specific naming policy strategy to an object's field during serialization and deserialization.

Parameters:
fieldNamingStrategy - the actual naming strategy to apply to the fields
Returns:
a reference to this GsonBuilder object to fulfill the "Builder" pattern
Since:
1.3

setExclusionStrategies

public GsonBuilder setExclusionStrategies(ExclusionStrategy... strategies)
Configures Gson to apply a set of exclusion strategies during both serialization and deserialization. Each of the strategies will be applied as a disjunction rule. This means that if one of the strategies suggests that a field (or class) should be skipped then that field (or object) is skipped during serializaiton/deserialization.

Parameters:
strategies - the set of strategy object to apply during object (de)serialization.
Returns:
a reference to this GsonBuilder object to fulfill the "Builder" pattern
Since:
1.4

addSerializationExclusionStrategy

public GsonBuilder addSerializationExclusionStrategy(ExclusionStrategy strategy)
Configures Gson to apply the passed in exclusion strategy during serialization. If this method is invoked numerous times with different exclusion strategy objects then the exclusion strategies that were added will be applied as a disjunction rule. This means that if one of the added exclusion strategies suggests that a field (or class) should be skipped then that field (or object) is skipped during its serialization.

Parameters:
strategy - an exclusion strategy to apply during serialization.
Returns:
a reference to this GsonBuilder object to fulfill the "Builder" pattern
Since:
1.7

addDeserializationExclusionStrategy

public GsonBuilder addDeserializationExclusionStrategy(ExclusionStrategy strategy)
Configures Gson to apply the passed in exclusion strategy during deserialization. If this method is invoked numerous times with different exclusion strategy objects then the exclusion strategies that were added will be applied as a disjunction rule. This means that if one of the added exclusion strategies suggests that a field (or class) should be skipped then that field (or object) is skipped during its deserialization.

Parameters:
strategy - an exclusion strategy to apply during deserialization.
Returns:
a reference to this GsonBuilder object to fulfill the "Builder" pattern
Since:
1.7

setPrettyPrinting

public GsonBuilder setPrettyPrinting()
Configures Gson to output Json that fits in a page for pretty printing. This option only affects Json serialization.

Returns:
a reference to this GsonBuilder object to fulfill the "Builder" pattern

disableHtmlEscaping

public GsonBuilder disableHtmlEscaping()
By default, Gson escapes HTML characters such as < > etc. Use this option to configure Gson to pass-through HTML characters as is.

Returns:
a reference to this GsonBuilder object to fulfill the "Builder" pattern
Since:
1.3

setDateFormat

public GsonBuilder setDateFormat(String pattern)
Configures Gson to serialize Date objects according to the pattern provided. You can call this method or setDateFormat(int) multiple times, but only the last invocation will be used to decide the serialization format.

The date format will be used to serialize and deserialize Date, Timestamp and Date.

Note that this pattern must abide by the convention provided by SimpleDateFormat class. See the documentation in SimpleDateFormat for more information on valid date and time patterns.

Parameters:
pattern - the pattern that dates will be serialized/deserialized to/from
Returns:
a reference to this GsonBuilder object to fulfill the "Builder" pattern
Since:
1.2

setDateFormat

public GsonBuilder setDateFormat(int style)
Configures Gson to to serialize Date objects according to the style value provided. You can call this method or setDateFormat(String) multiple times, but only the last invocation will be used to decide the serialization format.

Note that this style value should be one of the predefined constants in the DateFormat class. See the documentation in DateFormat for more information on the valid style constants.

Parameters:
style - the predefined date style that date objects will be serialized/deserialized to/from
Returns:
a reference to this GsonBuilder object to fulfill the "Builder" pattern
Since:
1.2

setDateFormat

public GsonBuilder setDateFormat(int dateStyle,
                                 int timeStyle)
Configures Gson to to serialize Date objects according to the style value provided. You can call this method or setDateFormat(String) multiple times, but only the last invocation will be used to decide the serialization format.

Note that this style value should be one of the predefined constants in the DateFormat class. See the documentation in DateFormat for more information on the valid style constants.

Parameters:
dateStyle - the predefined date style that date objects will be serialized/deserialized to/from
timeStyle - the predefined style for the time portion of the date objects
Returns:
a reference to this GsonBuilder object to fulfill the "Builder" pattern
Since:
1.2

registerTypeAdapter

public GsonBuilder registerTypeAdapter(Type type,
                                       Object typeAdapter)
Configures Gson for custom serialization or deserialization. This method combines the registration of an TypeAdapter, InstanceCreator, JsonSerializer, and a JsonDeserializer. It is best used when a single object typeAdapter implements all the required interfaces for custom serialization with Gson. If a type adapter was previously registered for the specified type, it is overwritten.

This registers the type specified and no other types: you must manually register related types! For example, applications registering boolean.class should also register Boolean.class.

Parameters:
type - the type definition for the type adapter being registered
typeAdapter - This object must implement at least one of the TypeAdapter, InstanceCreator, JsonSerializer, and a JsonDeserializer interfaces.
Returns:
a reference to this GsonBuilder object to fulfill the "Builder" pattern

registerTypeAdapterFactory

public GsonBuilder registerTypeAdapterFactory(TypeAdapterFactory factory)
Register a factory for type adapters. Registering a factory is useful when the type adapter needs to be configured based on the type of the field being processed. Gson is designed to handle a large number of factories, so you should consider registering them to be at par with registering an individual type adapter.

Since:
2.1

registerTypeHierarchyAdapter

public GsonBuilder registerTypeHierarchyAdapter(Class<?> baseType,
                                                Object typeAdapter)
Configures Gson for custom serialization or deserialization for an inheritance type hierarchy. This method combines the registration of a TypeAdapter, JsonSerializer and a JsonDeserializer. If a type adapter was previously registered for the specified type hierarchy, it is overridden. If a type adapter is registered for a specific type in the type hierarchy, it will be invoked instead of the one registered for the type hierarchy.

Parameters:
baseType - the class definition for the type adapter being registered for the base class or interface
typeAdapter - This object must implement at least one of TypeAdapter, JsonSerializer or JsonDeserializer interfaces.
Returns:
a reference to this GsonBuilder object to fulfill the "Builder" pattern
Since:
1.7

serializeSpecialFloatingPointValues

public GsonBuilder serializeSpecialFloatingPointValues()
Section 2.4 of JSON specification disallows special double values (NaN, Infinity, -Infinity). However, Javascript specification (see section 4.3.20, 4.3.22, 4.3.23) allows these values as valid Javascript values. Moreover, most JavaScript engines will accept these special values in JSON without problem. So, at a practical level, it makes sense to accept these values as valid JSON even though JSON specification disallows them.

Gson always accepts these special values during deserialization. However, it outputs strictly compliant JSON. Hence, if it encounters a float value Float.NaN, Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY, or a double value Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, it will throw an IllegalArgumentException. This method provides a way to override the default behavior when you know that the JSON receiver will be able to handle these special values.

Returns:
a reference to this GsonBuilder object to fulfill the "Builder" pattern
Since:
1.3

create

public Gson create()
Creates a Gson instance based on the current configuration. This method is free of side-effects to this GsonBuilder instance and hence can be called multiple times.

Returns:
an instance of Gson configured with the options currently set in this builder


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/InstanceCreator.html000066400000000000000000000273341316034351600274010ustar00rootroot00000000000000 InstanceCreator (Gson 2.3.1 API)

com.google.gson
Interface InstanceCreator<T>

Type Parameters:
T - the type of object that will be created by this implementation.

public interface InstanceCreator<T>

This interface is implemented to create instances of a class that does not define a no-args constructor. If you can modify the class, you should instead add a private, or public no-args constructor. However, that is not possible for library classes, such as JDK classes, or a third-party library that you do not have source-code of. In such cases, you should define an instance creator for the class. Implementations of this interface should be registered with GsonBuilder.registerTypeAdapter(Type, Object) method before Gson will be able to use them.

Let us look at an example where defining an InstanceCreator might be useful. The Id class defined below does not have a default no-args constructor.

 public class Id<T> {
   private final Class<T> clazz;
   private final long value;
   public Id(Class<T> clazz, long value) {
     this.clazz = clazz;
     this.value = value;
   }
 }
 

If Gson encounters an object of type Id during deserialization, it will throw an exception. The easiest way to solve this problem will be to add a (public or private) no-args constructor as follows:

 private Id() {
   this(Object.class, 0L);
 }
 

However, let us assume that the developer does not have access to the source-code of the Id class, or does not want to define a no-args constructor for it. The developer can solve this problem by defining an InstanceCreator for Id:

 class IdInstanceCreator implements InstanceCreator<Id> {
   public Id createInstance(Type type) {
     return new Id(Object.class, 0L);
   }
 }
 

Note that it does not matter what the fields of the created instance contain since Gson will overwrite them with the deserialized values specified in Json. You should also ensure that a new object is returned, not a common object since its fields will be overwritten. The developer will need to register IdInstanceCreator with Gson as follows:

 Gson gson = new GsonBuilder().registerTypeAdapter(Id.class, new IdInstanceCreator()).create();
 

Author:
Inderjeet Singh, Joel Leitch

Method Summary
 T createInstance(Type type)
          Gson invokes this call-back method during deserialization to create an instance of the specified type.
 

Method Detail

createInstance

T createInstance(Type type)
Gson invokes this call-back method during deserialization to create an instance of the specified type. The fields of the returned instance are overwritten with the data present in the Json. Since the prior contents of the object are destroyed and overwritten, do not return an instance that is useful elsewhere. In particular, do not return a common instance, always use new to create a new instance.

Parameters:
type - the parameterized T represented as a Type.
Returns:
a default object instance of type T.


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/JsonArray.html000066400000000000000000001356031316034351600262240ustar00rootroot00000000000000 JsonArray (Gson 2.3.1 API)

com.google.gson
Class JsonArray

java.lang.Object
  extended by com.google.gson.JsonElement
      extended by com.google.gson.JsonArray
All Implemented Interfaces:
Iterable<JsonElement>

public final class JsonArray
extends JsonElement
implements Iterable<JsonElement>

A class representing an array type in Json. An array is a list of JsonElements each of which can be of a different type. This is an ordered list, meaning that the order in which elements are added is preserved.

Author:
Inderjeet Singh, Joel Leitch

Constructor Summary
JsonArray()
          Creates an empty JsonArray.
 
Method Summary
 void add(JsonElement element)
          Adds the specified element to self.
 void addAll(JsonArray array)
          Adds all the elements of the specified array to self.
 boolean contains(JsonElement element)
          Returns true if this array contains the specified element.
 boolean equals(Object o)
           
 JsonElement get(int i)
          Returns the ith element of the array.
 BigDecimal getAsBigDecimal()
          convenience method to get this array as a BigDecimal if it contains a single element.
 BigInteger getAsBigInteger()
          convenience method to get this array as a BigInteger if it contains a single element.
 boolean getAsBoolean()
          convenience method to get this array as a boolean if it contains a single element.
 byte getAsByte()
          convenience method to get this element as a primitive byte value.
 char getAsCharacter()
          convenience method to get this element as a primitive character value.
 double getAsDouble()
          convenience method to get this array as a double if it contains a single element.
 float getAsFloat()
          convenience method to get this array as a float if it contains a single element.
 int getAsInt()
          convenience method to get this array as an integer if it contains a single element.
 long getAsLong()
          convenience method to get this array as a long if it contains a single element.
 Number getAsNumber()
          convenience method to get this array as a Number if it contains a single element.
 short getAsShort()
          convenience method to get this array as a primitive short if it contains a single element.
 String getAsString()
          convenience method to get this array as a String if it contains a single element.
 int hashCode()
           
 Iterator<JsonElement> iterator()
          Returns an iterator to navigate the elemetns of the array.
 JsonElement remove(int index)
          Removes the element at the specified position in this array.
 boolean remove(JsonElement element)
          Removes the first occurrence of the specified element from this array, if it is present.
 JsonElement set(int index, JsonElement element)
          Replaces the element at the specified position in this array with the specified element.
 int size()
          Returns the number of elements in the array.
 
Methods inherited from class com.google.gson.JsonElement
getAsJsonArray, getAsJsonNull, getAsJsonObject, getAsJsonPrimitive, isJsonArray, isJsonNull, isJsonObject, isJsonPrimitive, toString
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Constructor Detail

JsonArray

public JsonArray()
Creates an empty JsonArray.

Method Detail

add

public void add(JsonElement element)
Adds the specified element to self.

Parameters:
element - the element that needs to be added to the array.

addAll

public void addAll(JsonArray array)
Adds all the elements of the specified array to self.

Parameters:
array - the array whose elements need to be added to the array.

set

public JsonElement set(int index,
                       JsonElement element)
Replaces the element at the specified position in this array with the specified element. Element can be null.

Parameters:
index - index of the element to replace
element - element to be stored at the specified position
Returns:
the element previously at the specified position
Throws:
IndexOutOfBoundsException - if the specified index is outside the array bounds

remove

public boolean remove(JsonElement element)
Removes the first occurrence of the specified element from this array, if it is present. If the array does not contain the element, it is unchanged.

Parameters:
element - element to be removed from this array, if present
Returns:
true if this array contained the specified element, false otherwise
Since:
2.3

remove

public JsonElement remove(int index)
Removes the element at the specified position in this array. Shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from the array.

Parameters:
index - index the index of the element to be removed
Returns:
the element previously at the specified position
Throws:
IndexOutOfBoundsException - if the specified index is outside the array bounds
Since:
2.3

contains

public boolean contains(JsonElement element)
Returns true if this array contains the specified element.

Parameters:
element - whose presence in this array is to be tested
Returns:
true if this array contains the specified element.
Since:
2.3

size

public int size()
Returns the number of elements in the array.

Returns:
the number of elements in the array.

iterator

public Iterator<JsonElement> iterator()
Returns an iterator to navigate the elemetns of the array. Since the array is an ordered list, the iterator navigates the elements in the order they were inserted.

Specified by:
iterator in interface Iterable<JsonElement>
Returns:
an iterator to navigate the elements of the array.

get

public JsonElement get(int i)
Returns the ith element of the array.

Parameters:
i - the index of the element that is being sought.
Returns:
the element present at the ith index.
Throws:
IndexOutOfBoundsException - if i is negative or greater than or equal to the size() of the array.

getAsNumber

public Number getAsNumber()
convenience method to get this array as a Number if it contains a single element.

Overrides:
getAsNumber in class JsonElement
Returns:
get this element as a number if it is single element array.
Throws:
ClassCastException - if the element in the array is of not a JsonPrimitive and is not a valid Number.
IllegalStateException - if the array has more than one element.

getAsString

public String getAsString()
convenience method to get this array as a String if it contains a single element.

Overrides:
getAsString in class JsonElement
Returns:
get this element as a String if it is single element array.
Throws:
ClassCastException - if the element in the array is of not a JsonPrimitive and is not a valid String.
IllegalStateException - if the array has more than one element.

getAsDouble

public double getAsDouble()
convenience method to get this array as a double if it contains a single element.

Overrides:
getAsDouble in class JsonElement
Returns:
get this element as a double if it is single element array.
Throws:
ClassCastException - if the element in the array is of not a JsonPrimitive and is not a valid double.
IllegalStateException - if the array has more than one element.

getAsBigDecimal

public BigDecimal getAsBigDecimal()
convenience method to get this array as a BigDecimal if it contains a single element.

Overrides:
getAsBigDecimal in class JsonElement
Returns:
get this element as a BigDecimal if it is single element array.
Throws:
ClassCastException - if the element in the array is of not a JsonPrimitive.
NumberFormatException - if the element at index 0 is not a valid BigDecimal.
IllegalStateException - if the array has more than one element.
Since:
1.2

getAsBigInteger

public BigInteger getAsBigInteger()
convenience method to get this array as a BigInteger if it contains a single element.

Overrides:
getAsBigInteger in class JsonElement
Returns:
get this element as a BigInteger if it is single element array.
Throws:
ClassCastException - if the element in the array is of not a JsonPrimitive.
NumberFormatException - if the element at index 0 is not a valid BigInteger.
IllegalStateException - if the array has more than one element.
Since:
1.2

getAsFloat

public float getAsFloat()
convenience method to get this array as a float if it contains a single element.

Overrides:
getAsFloat in class JsonElement
Returns:
get this element as a float if it is single element array.
Throws:
ClassCastException - if the element in the array is of not a JsonPrimitive and is not a valid float.
IllegalStateException - if the array has more than one element.

getAsLong

public long getAsLong()
convenience method to get this array as a long if it contains a single element.

Overrides:
getAsLong in class JsonElement
Returns:
get this element as a long if it is single element array.
Throws:
ClassCastException - if the element in the array is of not a JsonPrimitive and is not a valid long.
IllegalStateException - if the array has more than one element.

getAsInt

public int getAsInt()
convenience method to get this array as an integer if it contains a single element.

Overrides:
getAsInt in class JsonElement
Returns:
get this element as an integer if it is single element array.
Throws:
ClassCastException - if the element in the array is of not a JsonPrimitive and is not a valid integer.
IllegalStateException - if the array has more than one element.

getAsByte

public byte getAsByte()
Description copied from class: JsonElement
convenience method to get this element as a primitive byte value.

Overrides:
getAsByte in class JsonElement
Returns:
get this element as a primitive byte value.

getAsCharacter

public char getAsCharacter()
Description copied from class: JsonElement
convenience method to get this element as a primitive character value.

Overrides:
getAsCharacter in class JsonElement
Returns:
get this element as a primitive char value.

getAsShort

public short getAsShort()
convenience method to get this array as a primitive short if it contains a single element.

Overrides:
getAsShort in class JsonElement
Returns:
get this element as a primitive short if it is single element array.
Throws:
ClassCastException - if the element in the array is of not a JsonPrimitive and is not a valid short.
IllegalStateException - if the array has more than one element.

getAsBoolean

public boolean getAsBoolean()
convenience method to get this array as a boolean if it contains a single element.

Overrides:
getAsBoolean in class JsonElement
Returns:
get this element as a boolean if it is single element array.
Throws:
ClassCastException - if the element in the array is of not a JsonPrimitive and is not a valid boolean.
IllegalStateException - if the array has more than one element.

equals

public boolean equals(Object o)
Overrides:
equals in class Object

hashCode

public int hashCode()
Overrides:
hashCode in class Object


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/JsonDeserializationContext.html000066400000000000000000000246241316034351600316410ustar00rootroot00000000000000 JsonDeserializationContext (Gson 2.3.1 API)

com.google.gson
Interface JsonDeserializationContext


public interface JsonDeserializationContext

Context for deserialization that is passed to a custom deserializer during invocation of its JsonDeserializer.deserialize(JsonElement, Type, JsonDeserializationContext) method.

Author:
Inderjeet Singh, Joel Leitch

Method Summary
<T> T
deserialize(JsonElement json, Type typeOfT)
          Invokes default deserialization on the specified object.
 

Method Detail

deserialize

<T> T deserialize(JsonElement json,
                  Type typeOfT)
              throws JsonParseException
Invokes default deserialization on the specified object. It should never be invoked on the element received as a parameter of the JsonDeserializer.deserialize(JsonElement, Type, JsonDeserializationContext) method. Doing so will result in an infinite loop since Gson will in-turn call the custom deserializer again.

Type Parameters:
T - The type of the deserialized object.
Parameters:
json - the parse tree.
typeOfT - type of the expected return value.
Returns:
An object of type typeOfT.
Throws:
JsonParseException - if the parse tree does not contain expected data.


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/JsonDeserializer.html000066400000000000000000000313401316034351600275610ustar00rootroot00000000000000 JsonDeserializer (Gson 2.3.1 API)

com.google.gson
Interface JsonDeserializer<T>

Type Parameters:
T - type for which the deserializer is being registered. It is possible that a deserializer may be asked to deserialize a specific generic type of the T.

public interface JsonDeserializer<T>

Interface representing a custom deserializer for Json. You should write a custom deserializer, if you are not happy with the default deserialization done by Gson. You will also need to register this deserializer through GsonBuilder.registerTypeAdapter(Type, Object).

Let us look at example where defining a deserializer will be useful. The Id class defined below has two fields: clazz and value.

 public class Id<T> {
   private final Class<T> clazz;
   private final long value;
   public Id(Class<T> clazz, long value) {
     this.clazz = clazz;
     this.value = value;
   }
   public long getValue() {
     return value;
   }
 }
 

The default deserialization of Id(com.foo.MyObject.class, 20L) will require the Json string to be {"clazz":com.foo.MyObject,"value":20}. Suppose, you already know the type of the field that the Id will be deserialized into, and hence just want to deserialize it from a Json string 20. You can achieve that by writing a custom deserializer:

 class IdDeserializer implements JsonDeserializer<Id>() {
   public Id deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
       throws JsonParseException {
     return new Id((Class)typeOfT, id.getValue());
   }
 

You will also need to register IdDeserializer with Gson as follows:

 Gson gson = new GsonBuilder().registerTypeAdapter(Id.class, new IdDeserializer()).create();
 

New applications should prefer TypeAdapter, whose streaming API is more efficient than this interface's tree API.

Author:
Inderjeet Singh, Joel Leitch

Method Summary
 T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
          Gson invokes this call-back method during deserialization when it encounters a field of the specified type.
 

Method Detail

deserialize

T deserialize(JsonElement json,
              Type typeOfT,
              JsonDeserializationContext context)
              throws JsonParseException
Gson invokes this call-back method during deserialization when it encounters a field of the specified type.

In the implementation of this call-back method, you should consider invoking JsonDeserializationContext.deserialize(JsonElement, Type) method to create objects for any non-trivial field of the returned object. However, you should never invoke it on the the same type passing json since that will cause an infinite loop (Gson will call your call-back method again).

Parameters:
json - The Json data being deserialized
typeOfT - The type of the Object to deserialize to
Returns:
a deserialized object of the specified type typeOfT which is a subclass of T
Throws:
JsonParseException - if json is not in the expected format of typeofT


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/JsonElement.html000066400000000000000000001267701316034351600265440ustar00rootroot00000000000000 JsonElement (Gson 2.3.1 API)

com.google.gson
Class JsonElement

java.lang.Object
  extended by com.google.gson.JsonElement
Direct Known Subclasses:
JsonArray, JsonNull, JsonObject, JsonPrimitive

public abstract class JsonElement
extends Object

A class representing an element of Json. It could either be a JsonObject, a JsonArray, a JsonPrimitive or a JsonNull.

Author:
Inderjeet Singh, Joel Leitch

Constructor Summary
JsonElement()
           
 
Method Summary
 BigDecimal getAsBigDecimal()
          convenience method to get this element as a BigDecimal.
 BigInteger getAsBigInteger()
          convenience method to get this element as a BigInteger.
 boolean getAsBoolean()
          convenience method to get this element as a boolean value.
 byte getAsByte()
          convenience method to get this element as a primitive byte value.
 char getAsCharacter()
          convenience method to get this element as a primitive character value.
 double getAsDouble()
          convenience method to get this element as a primitive double value.
 float getAsFloat()
          convenience method to get this element as a primitive float value.
 int getAsInt()
          convenience method to get this element as a primitive integer value.
 JsonArray getAsJsonArray()
          convenience method to get this element as a JsonArray.
 JsonNull getAsJsonNull()
          convenience method to get this element as a JsonNull.
 JsonObject getAsJsonObject()
          convenience method to get this element as a JsonObject.
 JsonPrimitive getAsJsonPrimitive()
          convenience method to get this element as a JsonPrimitive.
 long getAsLong()
          convenience method to get this element as a primitive long value.
 Number getAsNumber()
          convenience method to get this element as a Number.
 short getAsShort()
          convenience method to get this element as a primitive short value.
 String getAsString()
          convenience method to get this element as a string value.
 boolean isJsonArray()
          provides check for verifying if this element is an array or not.
 boolean isJsonNull()
          provides check for verifying if this element represents a null value or not.
 boolean isJsonObject()
          provides check for verifying if this element is a Json object or not.
 boolean isJsonPrimitive()
          provides check for verifying if this element is a primitive or not.
 String toString()
          Returns a String representation of this element.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

JsonElement

public JsonElement()
Method Detail

isJsonArray

public boolean isJsonArray()
provides check for verifying if this element is an array or not.

Returns:
true if this element is of type JsonArray, false otherwise.

isJsonObject

public boolean isJsonObject()
provides check for verifying if this element is a Json object or not.

Returns:
true if this element is of type JsonObject, false otherwise.

isJsonPrimitive

public boolean isJsonPrimitive()
provides check for verifying if this element is a primitive or not.

Returns:
true if this element is of type JsonPrimitive, false otherwise.

isJsonNull

public boolean isJsonNull()
provides check for verifying if this element represents a null value or not.

Returns:
true if this element is of type JsonNull, false otherwise.
Since:
1.2

getAsJsonObject

public JsonObject getAsJsonObject()
convenience method to get this element as a JsonObject. If the element is of some other type, a IllegalStateException will result. Hence it is best to use this method after ensuring that this element is of the desired type by calling isJsonObject() first.

Returns:
get this element as a JsonObject.
Throws:
IllegalStateException - if the element is of another type.

getAsJsonArray

public JsonArray getAsJsonArray()
convenience method to get this element as a JsonArray. If the element is of some other type, a IllegalStateException will result. Hence it is best to use this method after ensuring that this element is of the desired type by calling isJsonArray() first.

Returns:
get this element as a JsonArray.
Throws:
IllegalStateException - if the element is of another type.

getAsJsonPrimitive

public JsonPrimitive getAsJsonPrimitive()
convenience method to get this element as a JsonPrimitive. If the element is of some other type, a IllegalStateException will result. Hence it is best to use this method after ensuring that this element is of the desired type by calling isJsonPrimitive() first.

Returns:
get this element as a JsonPrimitive.
Throws:
IllegalStateException - if the element is of another type.

getAsJsonNull

public JsonNull getAsJsonNull()
convenience method to get this element as a JsonNull. If the element is of some other type, a IllegalStateException will result. Hence it is best to use this method after ensuring that this element is of the desired type by calling isJsonNull() first.

Returns:
get this element as a JsonNull.
Throws:
IllegalStateException - if the element is of another type.
Since:
1.2

getAsBoolean

public boolean getAsBoolean()
convenience method to get this element as a boolean value.

Returns:
get this element as a primitive boolean value.
Throws:
ClassCastException - if the element is of not a JsonPrimitive and is not a valid boolean value.
IllegalStateException - if the element is of the type JsonArray but contains more than a single element.

getAsNumber

public Number getAsNumber()
convenience method to get this element as a Number.

Returns:
get this element as a Number.
Throws:
ClassCastException - if the element is of not a JsonPrimitive and is not a valid number.
IllegalStateException - if the element is of the type JsonArray but contains more than a single element.

getAsString

public String getAsString()
convenience method to get this element as a string value.

Returns:
get this element as a string value.
Throws:
ClassCastException - if the element is of not a JsonPrimitive and is not a valid string value.
IllegalStateException - if the element is of the type JsonArray but contains more than a single element.

getAsDouble

public double getAsDouble()
convenience method to get this element as a primitive double value.

Returns:
get this element as a primitive double value.
Throws:
ClassCastException - if the element is of not a JsonPrimitive and is not a valid double value.
IllegalStateException - if the element is of the type JsonArray but contains more than a single element.

getAsFloat

public float getAsFloat()
convenience method to get this element as a primitive float value.

Returns:
get this element as a primitive float value.
Throws:
ClassCastException - if the element is of not a JsonPrimitive and is not a valid float value.
IllegalStateException - if the element is of the type JsonArray but contains more than a single element.

getAsLong

public long getAsLong()
convenience method to get this element as a primitive long value.

Returns:
get this element as a primitive long value.
Throws:
ClassCastException - if the element is of not a JsonPrimitive and is not a valid long value.
IllegalStateException - if the element is of the type JsonArray but contains more than a single element.

getAsInt

public int getAsInt()
convenience method to get this element as a primitive integer value.

Returns:
get this element as a primitive integer value.
Throws:
ClassCastException - if the element is of not a JsonPrimitive and is not a valid integer value.
IllegalStateException - if the element is of the type JsonArray but contains more than a single element.

getAsByte

public byte getAsByte()
convenience method to get this element as a primitive byte value.

Returns:
get this element as a primitive byte value.
Throws:
ClassCastException - if the element is of not a JsonPrimitive and is not a valid byte value.
IllegalStateException - if the element is of the type JsonArray but contains more than a single element.
Since:
1.3

getAsCharacter

public char getAsCharacter()
convenience method to get this element as a primitive character value.

Returns:
get this element as a primitive char value.
Throws:
ClassCastException - if the element is of not a JsonPrimitive and is not a valid char value.
IllegalStateException - if the element is of the type JsonArray but contains more than a single element.
Since:
1.3

getAsBigDecimal

public BigDecimal getAsBigDecimal()
convenience method to get this element as a BigDecimal.

Returns:
get this element as a BigDecimal.
Throws:
ClassCastException - if the element is of not a JsonPrimitive. * @throws NumberFormatException if the element is not a valid BigDecimal.
IllegalStateException - if the element is of the type JsonArray but contains more than a single element.
Since:
1.2

getAsBigInteger

public BigInteger getAsBigInteger()
convenience method to get this element as a BigInteger.

Returns:
get this element as a BigInteger.
Throws:
ClassCastException - if the element is of not a JsonPrimitive.
NumberFormatException - if the element is not a valid BigInteger.
IllegalStateException - if the element is of the type JsonArray but contains more than a single element.
Since:
1.2

getAsShort

public short getAsShort()
convenience method to get this element as a primitive short value.

Returns:
get this element as a primitive short value.
Throws:
ClassCastException - if the element is of not a JsonPrimitive and is not a valid short value.
IllegalStateException - if the element is of the type JsonArray but contains more than a single element.

toString

public String toString()
Returns a String representation of this element.

Overrides:
toString in class Object


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/JsonIOException.html000066400000000000000000000420141316034351600273250ustar00rootroot00000000000000 JsonIOException (Gson 2.3.1 API)

com.google.gson
Class JsonIOException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by java.lang.RuntimeException
              extended by com.google.gson.JsonParseException
                  extended by com.google.gson.JsonIOException
All Implemented Interfaces:
Serializable

public final class JsonIOException
extends JsonParseException

This exception is raised when Gson was unable to read an input stream or write to one.

Author:
Inderjeet Singh, Joel Leitch
See Also:
Serialized Form

Constructor Summary
JsonIOException(String msg)
           
JsonIOException(String msg, Throwable cause)
           
JsonIOException(Throwable cause)
          Creates exception with the specified cause.
 
Method Summary
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

JsonIOException

public JsonIOException(String msg)

JsonIOException

public JsonIOException(String msg,
                       Throwable cause)

JsonIOException

public JsonIOException(Throwable cause)
Creates exception with the specified cause. Consider using JsonIOException(String, Throwable) instead if you can describe what happened.

Parameters:
cause - root exception that caused this exception to be thrown.


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/JsonNull.html000066400000000000000000000420641316034351600260560ustar00rootroot00000000000000 JsonNull (Gson 2.3.1 API)

com.google.gson
Class JsonNull

java.lang.Object
  extended by com.google.gson.JsonElement
      extended by com.google.gson.JsonNull

public final class JsonNull
extends JsonElement

A class representing a Json null value.

Since:
1.2
Author:
Inderjeet Singh, Joel Leitch

Field Summary
static JsonNull INSTANCE
          singleton for JsonNull
 
Constructor Summary
JsonNull()
          Deprecated. 
 
Method Summary
 boolean equals(Object other)
          All instances of JsonNull are the same
 int hashCode()
          All instances of JsonNull have the same hash code since they are indistinguishable
 
Methods inherited from class com.google.gson.JsonElement
getAsBigDecimal, getAsBigInteger, getAsBoolean, getAsByte, getAsCharacter, getAsDouble, getAsFloat, getAsInt, getAsJsonArray, getAsJsonNull, getAsJsonObject, getAsJsonPrimitive, getAsLong, getAsNumber, getAsShort, getAsString, isJsonArray, isJsonNull, isJsonObject, isJsonPrimitive, toString
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Field Detail

INSTANCE

public static final JsonNull INSTANCE
singleton for JsonNull

Since:
1.8
Constructor Detail

JsonNull

@Deprecated
public JsonNull()
Deprecated. 

Creates a new JsonNull object. Deprecated since Gson version 1.8. Use INSTANCE instead

Method Detail

hashCode

public int hashCode()
All instances of JsonNull have the same hash code since they are indistinguishable

Overrides:
hashCode in class Object

equals

public boolean equals(Object other)
All instances of JsonNull are the same

Overrides:
equals in class Object


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/JsonObject.html000066400000000000000000001002571316034351600263510ustar00rootroot00000000000000 JsonObject (Gson 2.3.1 API)

com.google.gson
Class JsonObject

java.lang.Object
  extended by com.google.gson.JsonElement
      extended by com.google.gson.JsonObject

public final class JsonObject
extends JsonElement

A class representing an object type in Json. An object consists of name-value pairs where names are strings, and values are any other type of JsonElement. This allows for a creating a tree of JsonElements. The member elements of this object are maintained in order they were added.

Author:
Inderjeet Singh, Joel Leitch

Constructor Summary
JsonObject()
           
 
Method Summary
 void add(String property, JsonElement value)
          Adds a member, which is a name-value pair, to self.
 void addProperty(String property, Boolean value)
          Convenience method to add a boolean member.
 void addProperty(String property, Character value)
          Convenience method to add a char member.
 void addProperty(String property, Number value)
          Convenience method to add a primitive member.
 void addProperty(String property, String value)
          Convenience method to add a primitive member.
 Set<Map.Entry<String,JsonElement>> entrySet()
          Returns a set of members of this object.
 boolean equals(Object o)
           
 JsonElement get(String memberName)
          Returns the member with the specified name.
 JsonArray getAsJsonArray(String memberName)
          Convenience method to get the specified member as a JsonArray.
 JsonObject getAsJsonObject(String memberName)
          Convenience method to get the specified member as a JsonObject.
 JsonPrimitive getAsJsonPrimitive(String memberName)
          Convenience method to get the specified member as a JsonPrimitive element.
 boolean has(String memberName)
          Convenience method to check if a member with the specified name is present in this object.
 int hashCode()
           
 JsonElement remove(String property)
          Removes the property from this JsonObject.
 
Methods inherited from class com.google.gson.JsonElement
getAsBigDecimal, getAsBigInteger, getAsBoolean, getAsByte, getAsCharacter, getAsDouble, getAsFloat, getAsInt, getAsJsonArray, getAsJsonNull, getAsJsonObject, getAsJsonPrimitive, getAsLong, getAsNumber, getAsShort, getAsString, isJsonArray, isJsonNull, isJsonObject, isJsonPrimitive, toString
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Constructor Detail

JsonObject

public JsonObject()
Method Detail

add

public void add(String property,
                JsonElement value)
Adds a member, which is a name-value pair, to self. The name must be a String, but the value can be an arbitrary JsonElement, thereby allowing you to build a full tree of JsonElements rooted at this node.

Parameters:
property - name of the member.
value - the member object.

remove

public JsonElement remove(String property)
Removes the property from this JsonObject.

Parameters:
property - name of the member that should be removed.
Returns:
the JsonElement object that is being removed.
Since:
1.3

addProperty

public void addProperty(String property,
                        String value)
Convenience method to add a primitive member. The specified value is converted to a JsonPrimitive of String.

Parameters:
property - name of the member.
value - the string value associated with the member.

addProperty

public void addProperty(String property,
                        Number value)
Convenience method to add a primitive member. The specified value is converted to a JsonPrimitive of Number.

Parameters:
property - name of the member.
value - the number value associated with the member.

addProperty

public void addProperty(String property,
                        Boolean value)
Convenience method to add a boolean member. The specified value is converted to a JsonPrimitive of Boolean.

Parameters:
property - name of the member.
value - the number value associated with the member.

addProperty

public void addProperty(String property,
                        Character value)
Convenience method to add a char member. The specified value is converted to a JsonPrimitive of Character.

Parameters:
property - name of the member.
value - the number value associated with the member.

entrySet

public Set<Map.Entry<String,JsonElement>> entrySet()
Returns a set of members of this object. The set is ordered, and the order is in which the elements were added.

Returns:
a set of members of this object.

has

public boolean has(String memberName)
Convenience method to check if a member with the specified name is present in this object.

Parameters:
memberName - name of the member that is being checked for presence.
Returns:
true if there is a member with the specified name, false otherwise.

get

public JsonElement get(String memberName)
Returns the member with the specified name.

Parameters:
memberName - name of the member that is being requested.
Returns:
the member matching the name. Null if no such member exists.

getAsJsonPrimitive

public JsonPrimitive getAsJsonPrimitive(String memberName)
Convenience method to get the specified member as a JsonPrimitive element.

Parameters:
memberName - name of the member being requested.
Returns:
the JsonPrimitive corresponding to the specified member.

getAsJsonArray

public JsonArray getAsJsonArray(String memberName)
Convenience method to get the specified member as a JsonArray.

Parameters:
memberName - name of the member being requested.
Returns:
the JsonArray corresponding to the specified member.

getAsJsonObject

public JsonObject getAsJsonObject(String memberName)
Convenience method to get the specified member as a JsonObject.

Parameters:
memberName - name of the member being requested.
Returns:
the JsonObject corresponding to the specified member.

equals

public boolean equals(Object o)
Overrides:
equals in class Object

hashCode

public int hashCode()
Overrides:
hashCode in class Object


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/JsonParseException.html000066400000000000000000000455771316034351600301110ustar00rootroot00000000000000 JsonParseException (Gson 2.3.1 API)

com.google.gson
Class JsonParseException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by java.lang.RuntimeException
              extended by com.google.gson.JsonParseException
All Implemented Interfaces:
Serializable
Direct Known Subclasses:
JsonIOException, JsonSyntaxException

public class JsonParseException
extends RuntimeException

This exception is raised if there is a serious issue that occurs during parsing of a Json string. One of the main usages for this class is for the Gson infrastructure. If the incoming Json is bad/malicious, an instance of this exception is raised.

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

Author:
Inderjeet Singh, Joel Leitch
See Also:
Serialized Form

Constructor Summary
JsonParseException(String msg)
          Creates exception with the specified message.
JsonParseException(String msg, Throwable cause)
          Creates exception with the specified message and cause.
JsonParseException(Throwable cause)
          Creates exception with the specified cause.
 
Method Summary
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

JsonParseException

public JsonParseException(String msg)
Creates exception with the specified message. If you are wrapping another exception, consider using JsonParseException(String, Throwable) instead.

Parameters:
msg - error message describing a possible cause of this exception.

JsonParseException

public JsonParseException(String msg,
                          Throwable cause)
Creates exception with the specified message and cause.

Parameters:
msg - error message describing what happened.
cause - root exception that caused this exception to be thrown.

JsonParseException

public JsonParseException(Throwable cause)
Creates exception with the specified cause. Consider using JsonParseException(String, Throwable) instead if you can describe what happened.

Parameters:
cause - root exception that caused this exception to be thrown.


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/JsonParser.html000066400000000000000000000417341316034351600264030ustar00rootroot00000000000000 JsonParser (Gson 2.3.1 API)

com.google.gson
Class JsonParser

java.lang.Object
  extended by com.google.gson.JsonParser

public final class JsonParser
extends Object

A parser to parse Json into a parse tree of JsonElements

Since:
1.3
Author:
Inderjeet Singh, Joel Leitch

Constructor Summary
JsonParser()
           
 
Method Summary
 JsonElement parse(JsonReader json)
          Returns the next value from the JSON stream as a parse tree.
 JsonElement parse(Reader json)
          Parses the specified JSON string into a parse tree
 JsonElement parse(String json)
          Parses the specified JSON string into a parse tree
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

JsonParser

public JsonParser()
Method Detail

parse

public JsonElement parse(String json)
                  throws JsonSyntaxException
Parses the specified JSON string into a parse tree

Parameters:
json - JSON text
Returns:
a parse tree of JsonElements corresponding to the specified JSON
Throws:
JsonParseException - if the specified text is not valid JSON
JsonSyntaxException
Since:
1.3

parse

public JsonElement parse(Reader json)
                  throws JsonIOException,
                         JsonSyntaxException
Parses the specified JSON string into a parse tree

Parameters:
json - JSON text
Returns:
a parse tree of JsonElements corresponding to the specified JSON
Throws:
JsonParseException - if the specified text is not valid JSON
JsonIOException
JsonSyntaxException
Since:
1.3

parse

public JsonElement parse(JsonReader json)
                  throws JsonIOException,
                         JsonSyntaxException
Returns the next value from the JSON stream as a parse tree.

Throws:
JsonParseException - if there is an IOException or if the specified text is not valid JSON
JsonIOException
JsonSyntaxException
Since:
1.6


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/JsonPrimitive.html000066400000000000000000001060641316034351600271150ustar00rootroot00000000000000 JsonPrimitive (Gson 2.3.1 API)

com.google.gson
Class JsonPrimitive

java.lang.Object
  extended by com.google.gson.JsonElement
      extended by com.google.gson.JsonPrimitive

public final class JsonPrimitive
extends JsonElement

A class representing a Json primitive value. A primitive value is either a String, a Java primitive, or a Java primitive wrapper type.

Author:
Inderjeet Singh, Joel Leitch

Constructor Summary
JsonPrimitive(Boolean bool)
          Create a primitive containing a boolean value.
JsonPrimitive(Character c)
          Create a primitive containing a character.
JsonPrimitive(Number number)
          Create a primitive containing a Number.
JsonPrimitive(String string)
          Create a primitive containing a String value.
 
Method Summary
 boolean equals(Object obj)
           
 BigDecimal getAsBigDecimal()
          convenience method to get this element as a BigDecimal.
 BigInteger getAsBigInteger()
          convenience method to get this element as a BigInteger.
 boolean getAsBoolean()
          convenience method to get this element as a boolean value.
 byte getAsByte()
          convenience method to get this element as a primitive byte value.
 char getAsCharacter()
          convenience method to get this element as a primitive character value.
 double getAsDouble()
          convenience method to get this element as a primitive double.
 float getAsFloat()
          convenience method to get this element as a float.
 int getAsInt()
          convenience method to get this element as a primitive integer.
 long getAsLong()
          convenience method to get this element as a primitive long.
 Number getAsNumber()
          convenience method to get this element as a Number.
 short getAsShort()
          convenience method to get this element as a primitive short.
 String getAsString()
          convenience method to get this element as a String.
 int hashCode()
           
 boolean isBoolean()
          Check whether this primitive contains a boolean value.
 boolean isNumber()
          Check whether this primitive contains a Number.
 boolean isString()
          Check whether this primitive contains a String value.
 
Methods inherited from class com.google.gson.JsonElement
getAsJsonArray, getAsJsonNull, getAsJsonObject, getAsJsonPrimitive, isJsonArray, isJsonNull, isJsonObject, isJsonPrimitive, toString
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Constructor Detail

JsonPrimitive

public JsonPrimitive(Boolean bool)
Create a primitive containing a boolean value.

Parameters:
bool - the value to create the primitive with.

JsonPrimitive

public JsonPrimitive(Number number)
Create a primitive containing a Number.

Parameters:
number - the value to create the primitive with.

JsonPrimitive

public JsonPrimitive(String string)
Create a primitive containing a String value.

Parameters:
string - the value to create the primitive with.

JsonPrimitive

public JsonPrimitive(Character c)
Create a primitive containing a character. The character is turned into a one character String since Json only supports String.

Parameters:
c - the value to create the primitive with.
Method Detail

isBoolean

public boolean isBoolean()
Check whether this primitive contains a boolean value.

Returns:
true if this primitive contains a boolean value, false otherwise.

getAsBoolean

public boolean getAsBoolean()
convenience method to get this element as a boolean value.

Overrides:
getAsBoolean in class JsonElement
Returns:
get this element as a primitive boolean value.

isNumber

public boolean isNumber()
Check whether this primitive contains a Number.

Returns:
true if this primitive contains a Number, false otherwise.

getAsNumber

public Number getAsNumber()
convenience method to get this element as a Number.

Overrides:
getAsNumber in class JsonElement
Returns:
get this element as a Number.
Throws:
NumberFormatException - if the value contained is not a valid Number.

isString

public boolean isString()
Check whether this primitive contains a String value.

Returns:
true if this primitive contains a String value, false otherwise.

getAsString

public String getAsString()
convenience method to get this element as a String.

Overrides:
getAsString in class JsonElement
Returns:
get this element as a String.

getAsDouble

public double getAsDouble()
convenience method to get this element as a primitive double.

Overrides:
getAsDouble in class JsonElement
Returns:
get this element as a primitive double.
Throws:
NumberFormatException - if the value contained is not a valid double.

getAsBigDecimal

public BigDecimal getAsBigDecimal()
convenience method to get this element as a BigDecimal.

Overrides:
getAsBigDecimal in class JsonElement
Returns:
get this element as a BigDecimal.
Throws:
NumberFormatException - if the value contained is not a valid BigDecimal.

getAsBigInteger

public BigInteger getAsBigInteger()
convenience method to get this element as a BigInteger.

Overrides:
getAsBigInteger in class JsonElement
Returns:
get this element as a BigInteger.
Throws:
NumberFormatException - if the value contained is not a valid BigInteger.

getAsFloat

public float getAsFloat()
convenience method to get this element as a float.

Overrides:
getAsFloat in class JsonElement
Returns:
get this element as a float.
Throws:
NumberFormatException - if the value contained is not a valid float.

getAsLong

public long getAsLong()
convenience method to get this element as a primitive long.

Overrides:
getAsLong in class JsonElement
Returns:
get this element as a primitive long.
Throws:
NumberFormatException - if the value contained is not a valid long.

getAsShort

public short getAsShort()
convenience method to get this element as a primitive short.

Overrides:
getAsShort in class JsonElement
Returns:
get this element as a primitive short.
Throws:
NumberFormatException - if the value contained is not a valid short value.

getAsInt

public int getAsInt()
convenience method to get this element as a primitive integer.

Overrides:
getAsInt in class JsonElement
Returns:
get this element as a primitive integer.
Throws:
NumberFormatException - if the value contained is not a valid integer.

getAsByte

public byte getAsByte()
Description copied from class: JsonElement
convenience method to get this element as a primitive byte value.

Overrides:
getAsByte in class JsonElement
Returns:
get this element as a primitive byte value.

getAsCharacter

public char getAsCharacter()
Description copied from class: JsonElement
convenience method to get this element as a primitive character value.

Overrides:
getAsCharacter in class JsonElement
Returns:
get this element as a primitive char value.

hashCode

public int hashCode()
Overrides:
hashCode in class Object

equals

public boolean equals(Object obj)
Overrides:
equals in class Object


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/JsonSerializationContext.html000066400000000000000000000271141316034351600313250ustar00rootroot00000000000000 JsonSerializationContext (Gson 2.3.1 API)

com.google.gson
Interface JsonSerializationContext


public interface JsonSerializationContext

Context for serialization that is passed to a custom serializer during invocation of its JsonSerializer.serialize(Object, Type, JsonSerializationContext) method.

Author:
Inderjeet Singh, Joel Leitch

Method Summary
 JsonElement serialize(Object src)
          Invokes default serialization on the specified object.
 JsonElement serialize(Object src, Type typeOfSrc)
          Invokes default serialization on the specified object passing the specific type information.
 

Method Detail

serialize

JsonElement serialize(Object src)
Invokes default serialization on the specified object.

Parameters:
src - the object that needs to be serialized.
Returns:
a tree of JsonElements corresponding to the serialized form of src.

serialize

JsonElement serialize(Object src,
                      Type typeOfSrc)
Invokes default serialization on the specified object passing the specific type information. It should never be invoked on the element received as a parameter of the JsonSerializer.serialize(Object, Type, JsonSerializationContext) method. Doing so will result in an infinite loop since Gson will in-turn call the custom serializer again.

Parameters:
src - the object that needs to be serialized.
typeOfSrc - the actual genericized type of src object.
Returns:
a tree of JsonElements corresponding to the serialized form of src.


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/JsonSerializer.html000066400000000000000000000303611316034351600272520ustar00rootroot00000000000000 JsonSerializer (Gson 2.3.1 API)

com.google.gson
Interface JsonSerializer<T>

Type Parameters:
T - type for which the serializer is being registered. It is possible that a serializer may be asked to serialize a specific generic type of the T.

public interface JsonSerializer<T>

Interface representing a custom serializer for Json. You should write a custom serializer, if you are not happy with the default serialization done by Gson. You will also need to register this serializer through GsonBuilder.registerTypeAdapter(Type, Object).

Let us look at example where defining a serializer will be useful. The Id class defined below has two fields: clazz and value.

 public class Id<T> {
   private final Class<T> clazz;
   private final long value;

   public Id(Class<T> clazz, long value) {
     this.clazz = clazz;
     this.value = value;
   }

   public long getValue() {
     return value;
   }
 }
 

The default serialization of Id(com.foo.MyObject.class, 20L) will be {"clazz":com.foo.MyObject,"value":20}. Suppose, you just want the output to be the value instead, which is 20 in this case. You can achieve that by writing a custom serializer:

 class IdSerializer implements JsonSerializer<Id>() {
   public JsonElement serialize(Id id, Type typeOfId, JsonSerializationContext context) {
     return new JsonPrimitive(id.getValue());
   }
 }
 

You will also need to register IdSerializer with Gson as follows:

 Gson gson = new GsonBuilder().registerTypeAdapter(Id.class, new IdSerializer()).create();
 

New applications should prefer TypeAdapter, whose streaming API is more efficient than this interface's tree API.

Author:
Inderjeet Singh, Joel Leitch

Method Summary
 JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context)
          Gson invokes this call-back method during serialization when it encounters a field of the specified type.
 

Method Detail

serialize

JsonElement serialize(T src,
                      Type typeOfSrc,
                      JsonSerializationContext context)
Gson invokes this call-back method during serialization when it encounters a field of the specified type.

In the implementation of this call-back method, you should consider invoking JsonSerializationContext.serialize(Object, Type) method to create JsonElements for any non-trivial field of the src object. However, you should never invoke it on the src object itself since that will cause an infinite loop (Gson will call your call-back method again).

Parameters:
src - the object that needs to be converted to Json.
typeOfSrc - the actual type (fully genericized version) of the source object.
Returns:
a JsonElement corresponding to the specified object.


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/JsonStreamParser.html000066400000000000000000000454751316034351600275650ustar00rootroot00000000000000 JsonStreamParser (Gson 2.3.1 API)

com.google.gson
Class JsonStreamParser

java.lang.Object
  extended by com.google.gson.JsonStreamParser
All Implemented Interfaces:
Iterator<JsonElement>

public final class JsonStreamParser
extends Object
implements Iterator<JsonElement>

A streaming parser that allows reading of multiple JsonElements from the specified reader asynchronously.

This class is conditionally thread-safe (see Item 70, Effective Java second edition). To properly use this class across multiple threads, you will need to add some external synchronization. For example:

 JsonStreamParser parser = new JsonStreamParser("['first'] {'second':10} 'third'");
 JsonElement element;
 synchronized (parser) {  // synchronize on an object shared by threads
   if (parser.hasNext()) {
     element = parser.next();
   }
 }
 

Since:
1.4
Author:
Inderjeet Singh, Joel Leitch

Constructor Summary
JsonStreamParser(Reader reader)
           
JsonStreamParser(String json)
           
 
Method Summary
 boolean hasNext()
          Returns true if a JsonElement is available on the input for consumption
 JsonElement next()
          Returns the next available JsonElement on the reader.
 void remove()
          This optional Iterator method is not relevant for stream parsing and hence is not implemented.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

JsonStreamParser

public JsonStreamParser(String json)
Parameters:
json - The string containing JSON elements concatenated to each other.
Since:
1.4

JsonStreamParser

public JsonStreamParser(Reader reader)
Parameters:
reader - The data stream containing JSON elements concatenated to each other.
Since:
1.4
Method Detail

next

public JsonElement next()
                 throws JsonParseException
Returns the next available JsonElement on the reader. Null if none available.

Specified by:
next in interface Iterator<JsonElement>
Returns:
the next available JsonElement on the reader. Null if none available.
Throws:
JsonParseException - if the incoming stream is malformed JSON.
Since:
1.4

hasNext

public boolean hasNext()
Returns true if a JsonElement is available on the input for consumption

Specified by:
hasNext in interface Iterator<JsonElement>
Returns:
true if a JsonElement is available on the input, false otherwise
Since:
1.4

remove

public void remove()
This optional Iterator method is not relevant for stream parsing and hence is not implemented.

Specified by:
remove in interface Iterator<JsonElement>
Since:
1.4


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/JsonSyntaxException.html000066400000000000000000000423121316034351600303050ustar00rootroot00000000000000 JsonSyntaxException (Gson 2.3.1 API)

com.google.gson
Class JsonSyntaxException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by java.lang.RuntimeException
              extended by com.google.gson.JsonParseException
                  extended by com.google.gson.JsonSyntaxException
All Implemented Interfaces:
Serializable

public final class JsonSyntaxException
extends JsonParseException

This exception is raised when Gson attempts to read (or write) a malformed JSON element.

Author:
Inderjeet Singh, Joel Leitch
See Also:
Serialized Form

Constructor Summary
JsonSyntaxException(String msg)
           
JsonSyntaxException(String msg, Throwable cause)
           
JsonSyntaxException(Throwable cause)
          Creates exception with the specified cause.
 
Method Summary
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

JsonSyntaxException

public JsonSyntaxException(String msg)

JsonSyntaxException

public JsonSyntaxException(String msg,
                           Throwable cause)

JsonSyntaxException

public JsonSyntaxException(Throwable cause)
Creates exception with the specified cause. Consider using JsonSyntaxException(String, Throwable) instead if you can describe what actually happened.

Parameters:
cause - root exception that caused this exception to be thrown.


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/LongSerializationPolicy.html000066400000000000000000000464721316034351600311360ustar00rootroot00000000000000 LongSerializationPolicy (Gson 2.3.1 API)

com.google.gson
Enum LongSerializationPolicy

java.lang.Object
  extended by java.lang.Enum<LongSerializationPolicy>
      extended by com.google.gson.LongSerializationPolicy
All Implemented Interfaces:
Serializable, Comparable<LongSerializationPolicy>

public enum LongSerializationPolicy
extends Enum<LongSerializationPolicy>

Defines the expected format for a long or Long type when its serialized.

Since:
1.3
Author:
Inderjeet Singh, Joel Leitch

Enum Constant Summary
DEFAULT
          This is the "default" serialization policy that will output a long object as a JSON number.
STRING
          Serializes a long value as a quoted string.
 
Method Summary
abstract  JsonElement serialize(Long value)
          Serialize this value using this serialization policy.
static LongSerializationPolicy valueOf(String name)
          Returns the enum constant of this type with the specified name.
static LongSerializationPolicy[] values()
          Returns an array containing the constants of this enum type, in the order they are declared.
 
Methods inherited from class java.lang.Enum
clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf
 
Methods inherited from class java.lang.Object
getClass, notify, notifyAll, wait, wait, wait
 

Enum Constant Detail

DEFAULT

public static final LongSerializationPolicy DEFAULT
This is the "default" serialization policy that will output a long object as a JSON number. For example, assume an object has a long field named "f" then the serialized output would be: {"f":123}.


STRING

public static final LongSerializationPolicy STRING
Serializes a long value as a quoted string. For example, assume an object has a long field named "f" then the serialized output would be: {"f":"123"}.

Method Detail

values

public static LongSerializationPolicy[] values()
Returns an array containing the constants of this enum type, in the order they are declared. This method may be used to iterate over the constants as follows:
for (LongSerializationPolicy c : LongSerializationPolicy.values())
    System.out.println(c);

Returns:
an array containing the constants of this enum type, in the order they are declared

valueOf

public static LongSerializationPolicy valueOf(String name)
Returns the enum constant of this type with the specified name. The string must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)

Parameters:
name - the name of the enum constant to be returned.
Returns:
the enum constant with the specified name
Throws:
IllegalArgumentException - if this enum type has no constant with the specified name
NullPointerException - if the argument is null

serialize

public abstract JsonElement serialize(Long value)
Serialize this value using this serialization policy.

Parameters:
value - the long value to be serialized into a JsonElement
Returns:
the serialized version of value


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/TypeAdapter.html000066400000000000000000000755171316034351600265450ustar00rootroot00000000000000 TypeAdapter (Gson 2.3.1 API)

com.google.gson
Class TypeAdapter<T>

java.lang.Object
  extended by com.google.gson.TypeAdapter<T>

public abstract class TypeAdapter<T>
extends Object

Converts Java objects to and from JSON.

Defining a type's JSON form

By default Gson converts application classes to JSON using its built-in type adapters. If Gson's default JSON conversion isn't appropriate for a type, extend this class to customize the conversion. Here's an example of a type adapter for an (X,Y) coordinate point:
   public class PointAdapter extends TypeAdapter<Point> {
     public Point read(JsonReader reader) throws IOException {
       if (reader.peek() == JsonToken.NULL) {
         reader.nextNull();
         return null;
       }
       String xy = reader.nextString();
       String[] parts = xy.split(",");
       int x = Integer.parseInt(parts[0]);
       int y = Integer.parseInt(parts[1]);
       return new Point(x, y);
     }
     public void write(JsonWriter writer, Point value) throws IOException {
       if (value == null) {
         writer.nullValue();
         return;
       }
       String xy = value.getX() + "," + value.getY();
       writer.value(xy);
     }
   }
With this type adapter installed, Gson will convert Points to JSON as strings like "5,8" rather than objects like {"x":5,"y":8}. In this case the type adapter binds a rich Java class to a compact JSON value.

The read() method must read exactly one value and write() must write exactly one value. For primitive types this is means readers should make exactly one call to nextBoolean(), nextDouble(), nextInt(), nextLong(), nextString() or nextNull(). Writers should make exactly one call to one of value() or nullValue(). For arrays, type adapters should start with a call to beginArray(), convert all elements, and finish with a call to endArray(). For objects, they should start with beginObject(), convert the object, and finish with endObject(). Failing to convert a value or converting too many values may cause the application to crash.

Type adapters should be prepared to read null from the stream and write it to the stream. Alternatively, they should use nullSafe() method while registering the type adapter with Gson. If your Gson instance has been configured to GsonBuilder.serializeNulls(), these nulls will be written to the final document. Otherwise the value (and the corresponding name when writing to a JSON object) will be omitted automatically. In either case your type adapter must handle null.

To use a custom type adapter with Gson, you must register it with a GsonBuilder:

   GsonBuilder builder = new GsonBuilder();
   builder.registerTypeAdapter(Point.class, new PointAdapter());
   // if PointAdapter didn't check for nulls in its read/write methods, you should instead use
   // builder.registerTypeAdapter(Point.class, new PointAdapter().nullSafe());
   ...
   Gson gson = builder.create();
 

Since:
2.1

Constructor Summary
TypeAdapter()
           
 
Method Summary
 T fromJson(Reader in)
          Converts the JSON document in in to a Java object.
 T fromJson(String json)
          Converts the JSON document in json to a Java object.
 T fromJsonTree(JsonElement jsonTree)
          Converts jsonTree to a Java object.
 TypeAdapter<T> nullSafe()
          This wrapper method is used to make a type adapter null tolerant.
abstract  T read(JsonReader in)
          Reads one JSON value (an array, object, string, number, boolean or null) and converts it to a Java object.
 String toJson(T value)
          Converts value to a JSON document.
 void toJson(Writer out, T value)
          Converts value to a JSON document and writes it to out.
 JsonElement toJsonTree(T value)
          Converts value to a JSON tree.
abstract  void write(JsonWriter out, T value)
          Writes one JSON value (an array, object, string, number, boolean or null) for value.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

TypeAdapter

public TypeAdapter()
Method Detail

write

public abstract void write(JsonWriter out,
                           T value)
                    throws IOException
Writes one JSON value (an array, object, string, number, boolean or null) for value.

Parameters:
value - the Java object to write. May be null.
Throws:
IOException

toJson

public final void toJson(Writer out,
                         T value)
                  throws IOException
Converts value to a JSON document and writes it to out. Unlike Gson's similar toJson method, this write is strict. Create a lenient JsonWriter and call write(com.google.gson.stream.JsonWriter, Object) for lenient writing.

Parameters:
value - the Java object to convert. May be null.
Throws:
IOException
Since:
2.2

nullSafe

public final TypeAdapter<T> nullSafe()
This wrapper method is used to make a type adapter null tolerant. In general, a type adapter is required to handle nulls in write and read methods. Here is how this is typically done:
   Gson gson = new GsonBuilder().registerTypeAdapter(Foo.class,
   new TypeAdapter<Foo>() {
     public Foo read(JsonReader in) throws IOException {
       if (in.peek() == JsonToken.NULL) {
         in.nextNull();
         return null;
       }
       // read a Foo from in and return it
     }
     public void write(JsonWriter out, Foo src) throws IOException {
       if (src == null) {
         out.nullValue();
         return;
       }
       // write src as JSON to out
     }
   }).create();
 
You can avoid this boilerplate handling of nulls by wrapping your type adapter with this method. Here is how we will rewrite the above example:
   Gson gson = new GsonBuilder().registerTypeAdapter(Foo.class,
   new TypeAdapter<Foo>() {
     public Foo read(JsonReader in) throws IOException {
       // read a Foo from in and return it
     }
     public void write(JsonWriter out, Foo src) throws IOException {
       // write src as JSON to out
     }
   }.nullSafe()).create();
 
Note that we didn't need to check for nulls in our type adapter after we used nullSafe.


toJson

public final String toJson(T value)
                    throws IOException
Converts value to a JSON document. Unlike Gson's similar toJson method, this write is strict. Create a lenient JsonWriter and call write(com.google.gson.stream.JsonWriter, Object) for lenient writing.

Parameters:
value - the Java object to convert. May be null.
Throws:
IOException
Since:
2.2

toJsonTree

public final JsonElement toJsonTree(T value)
Converts value to a JSON tree.

Parameters:
value - the Java object to convert. May be null.
Returns:
the converted JSON tree. May be JsonNull.
Since:
2.2

read

public abstract T read(JsonReader in)
                throws IOException
Reads one JSON value (an array, object, string, number, boolean or null) and converts it to a Java object. Returns the converted object.

Returns:
the converted Java object. May be null.
Throws:
IOException

fromJson

public final T fromJson(Reader in)
                 throws IOException
Converts the JSON document in in to a Java object. Unlike Gson's similar fromJson method, this read is strict. Create a lenient JsonReader and call read(JsonReader) for lenient reading.

Returns:
the converted Java object. May be null.
Throws:
IOException
Since:
2.2

fromJson

public final T fromJson(String json)
                 throws IOException
Converts the JSON document in json to a Java object. Unlike Gson's similar fromJson method, this read is strict. Create a lenient JsonReader and call read(JsonReader) for lenient reading.

Returns:
the converted Java object. May be null.
Throws:
IOException
Since:
2.2

fromJsonTree

public final T fromJsonTree(JsonElement jsonTree)
Converts jsonTree to a Java object.

Parameters:
jsonTree - the Java object to convert. May be JsonNull.
Since:
2.2


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/TypeAdapterFactory.html000066400000000000000000000352331316034351600300640ustar00rootroot00000000000000 TypeAdapterFactory (Gson 2.3.1 API)

com.google.gson
Interface TypeAdapterFactory


public interface TypeAdapterFactory

Creates type adapters for set of related types. Type adapter factories are most useful when several types share similar structure in their JSON form.

Example: Converting enums to lowercase

In this example, we implement a factory that creates type adapters for all enums. The type adapters will write enums in lowercase, despite the fact that they're defined in CONSTANT_CASE in the corresponding Java model:
   public class LowercaseEnumTypeAdapterFactory implements TypeAdapterFactory {
     public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
       Class<T> rawType = (Class<T>) type.getRawType();
       if (!rawType.isEnum()) {
         return null;
       }

       final Map<String, T> lowercaseToConstant = new HashMap<String, T>();
       for (T constant : rawType.getEnumConstants()) {
         lowercaseToConstant.put(toLowercase(constant), constant);
       }

       return new TypeAdapter<T>() {
         public void write(JsonWriter out, T value) throws IOException {
           if (value == null) {
             out.nullValue();
           } else {
             out.value(toLowercase(value));
           }
         }

         public T read(JsonReader reader) throws IOException {
           if (reader.peek() == JsonToken.NULL) {
             reader.nextNull();
             return null;
           } else {
             return lowercaseToConstant.get(reader.nextString());
           }
         }
       };
     }

     private String toLowercase(Object o) {
       return o.toString().toLowerCase(Locale.US);
     }
   }
 

Type adapter factories select which types they provide type adapters for. If a factory cannot support a given type, it must return null when that type is passed to create(com.google.gson.Gson, com.google.gson.reflect.TypeToken). Factories should expect create() to be called on them for many types and should return null for most of those types. In the above example the factory returns null for calls to create() where type is not an enum.

A factory is typically called once per type, but the returned type adapter may be used many times. It is most efficient to do expensive work like reflection in create() so that the type adapter's read() and write() methods can be very fast. In this example the mapping from lowercase name to enum value is computed eagerly.

As with type adapters, factories must be registered with a GsonBuilder for them to take effect:

   GsonBuilder builder = new GsonBuilder();
  builder.registerTypeAdapterFactory(new LowercaseEnumTypeAdapterFactory());
  ...
  Gson gson = builder.create();
 
If multiple factories support the same type, the factory registered earlier takes precedence.

Example: composing other type adapters

In this example we implement a factory for Guava's Multiset collection type. The factory can be used to create type adapters for multisets of any element type: the type adapter for Multiset<String> is different from the type adapter for Multiset<URL>.

The type adapter delegates to another type adapter for the multiset elements. It figures out the element type by reflecting on the multiset's type token. A Gson is passed in to create for just this purpose:

   public class MultisetTypeAdapterFactory implements TypeAdapterFactory {
     public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
       Type type = typeToken.getType();
       if (typeToken.getRawType() != Multiset.class
           || !(type instanceof ParameterizedType)) {
         return null;
       }

       Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0];
       TypeAdapter<?> elementAdapter = gson.getAdapter(TypeToken.get(elementType));
       return (TypeAdapter<T>) newMultisetAdapter(elementAdapter);
     }

     private <E> TypeAdapter<Multiset<E>> newMultisetAdapter(
         final TypeAdapter<E> elementAdapter) {
       return new TypeAdapter<Multiset<E>>() {
         public void write(JsonWriter out, Multiset<E> value) throws IOException {
           if (value == null) {
             out.nullValue();
             return;
           }

           out.beginArray();
           for (Multiset.Entry<E> entry : value.entrySet()) {
             out.value(entry.getCount());
             elementAdapter.write(out, entry.getElement());
           }
           out.endArray();
         }

         public Multiset<E> read(JsonReader in) throws IOException {
           if (in.peek() == JsonToken.NULL) {
             in.nextNull();
             return null;
           }

           Multiset<E> result = LinkedHashMultiset.create();
           in.beginArray();
           while (in.hasNext()) {
             int count = in.nextInt();
             E element = elementAdapter.read(in);
             result.add(element, count);
           }
           in.endArray();
           return result;
         }
       };
     }
   }
 
Delegating from one type adapter to another is extremely powerful; it's the foundation of how Gson converts Java objects and collections. Whenever possible your factory should retrieve its delegate type adapter in the create() method; this ensures potentially-expensive type adapter creation happens only once.

Since:
2.1

Method Summary
<T> TypeAdapter<T>
create(Gson gson, TypeToken<T> type)
          Returns a type adapter for type, or null if this factory doesn't support type.
 

Method Detail

create

<T> TypeAdapter<T> create(Gson gson,
                          TypeToken<T> type)
Returns a type adapter for type, or null if this factory doesn't support type.



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/annotations/000077500000000000000000000000001316034351600257535ustar00rootroot00000000000000gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/annotations/Expose.html000066400000000000000000000300701316034351600301040ustar00rootroot00000000000000 Expose (Gson 2.3.1 API)

com.google.gson.annotations
Annotation Type Expose


@Retention(value=RUNTIME)
@Target(value=FIELD)
public @interface Expose

An annotation that indicates this member should be exposed for JSON serialization or deserialization.

This annotation has no effect unless you build Gson with a GsonBuilder and invoke GsonBuilder.excludeFieldsWithoutExposeAnnotation() method.

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

 public class User {
   @Expose private String firstName;
   @Expose(serialize = false) private String lastName;
   @Expose (serialize = false, deserialize = false) private String emailAddress;
   private String password;
 }
 

If you created Gson with new Gson(), the toJson() and fromJson() methods will use the password field along-with firstName, lastName, and emailAddress for serialization and deserialization. However, if you created Gson with Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create() then the toJson() and fromJson() methods of Gson will exclude the password field. This is because the password field is not marked with the @Expose annotation. Gson will also exclude lastName and emailAddress from serialization since serialize is set to false. Similarly, Gson will exclude emailAddress from deserialization since deserialize is set to false.

Note that another way to achieve the same effect would have been to just mark the password field as transient, and Gson would have excluded it even with default settings. The @Expose annotation is useful in a style of programming where you want to explicitly specify all fields that should get considered for serialization or deserialization.

Author:
Inderjeet Singh, Joel Leitch

Optional Element Summary
 boolean deserialize
          If true, the field marked with this annotation is deserialized from the JSON.
 boolean serialize
          If true, the field marked with this annotation is written out in the JSON while serializing.
 

serialize

public abstract boolean serialize
If true, the field marked with this annotation is written out in the JSON while serializing. If false, the field marked with this annotation is skipped from the serialized output. Defaults to true.

Since:
1.4
Default:
true

deserialize

public abstract boolean deserialize
If true, the field marked with this annotation is deserialized from the JSON. If false, the field marked with this annotation is skipped during deserialization. Defaults to true.

Since:
1.4
Default:
true


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/annotations/JsonAdapter.html000066400000000000000000000310521316034351600310540ustar00rootroot00000000000000 JsonAdapter (Gson 2.3.1 API)

com.google.gson.annotations
Annotation Type JsonAdapter


@Retention(value=RUNTIME)
@Target(value={TYPE,FIELD})
public @interface JsonAdapter

An annotation that indicates the Gson TypeAdapter to use with a class or field.

Here is an example of how this annotation is used:

 @JsonAdapter(UserJsonAdapter.class)
 public class User {
   public final String firstName, lastName;
   private User(String firstName, String lastName) {
     this.firstName = firstName;
     this.lastName = lastName;
   }
 }
 public class UserJsonAdapter extends TypeAdapter<User> {
   @Override public void write(JsonWriter out, User user) throws IOException {
     // implement write: combine firstName and lastName into name
     out.beginObject();
     out.name("name");
     out.value(user.firstName + " " + user.lastName);
     out.endObject();
     // implement the write method
   }
   @Override public User read(JsonReader in) throws IOException {
     // implement read: split name into firstName and lastName
     in.beginObject();
     in.nextName();
     String[] nameParts = in.nextString().split(" ");
     in.endObject();
     return new User(nameParts[0], nameParts[1]);
   }
 }
 
Since User class specified UserJsonAdapter.class in @JsonAdapter annotation, it will automatically be invoked to serialize/deserialize User instances.

Here is an example of how to apply this annotation to a field.

 private static final class Gadget {
   @JsonAdapter(UserJsonAdapter2.class)
   final User user;
   Gadget(User user) {
     this.user = user;
   }
 }
 
It's possible to specify different type adapters on a field, that field's type, and in the GsonBuilder. Field annotations take precedence over GsonBuilder-registered type adapters, which in turn take precedence over annotated types.

The class referenced by this annotation must be either a TypeAdapter or a TypeAdapterFactory. Using the factory interface makes it possible to delegate to the enclosing Gson instance.

Since:
2.3
Author:
Inderjeet Singh, Joel Leitch, Jesse Wilson

Required Element Summary
 Class<?> value
          Either a TypeAdapter or TypeAdapterFactory.
 

Element Detail

value

public abstract Class<?> value
Either a TypeAdapter or TypeAdapterFactory.



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/annotations/SerializedName.html000066400000000000000000000264561316034351600315520ustar00rootroot00000000000000 SerializedName (Gson 2.3.1 API)

com.google.gson.annotations
Annotation Type SerializedName


@Retention(value=RUNTIME)
@Target(value=FIELD)
public @interface SerializedName

An annotation that indicates this member should be serialized to JSON with the provided name value as its field name.

This annotation will override any FieldNamingPolicy, including the default field naming policy, that may have been set on the Gson instance. A different naming policy can set using the GsonBuilder class. See GsonBuilder.setFieldNamingPolicy(com.google.gson.FieldNamingPolicy) for more information.

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

 public class SomeClassWithFields {
   @SerializedName("name") private final String someField;
   private final String someOtherField;

   public SomeClassWithFields(String a, String b) {
     this.someField = a;
     this.someOtherField = b;
   }
 }
 

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

 SomeClassWithFields objectToSerialize = new SomeClassWithFields("a", "b");
 Gson gson = new Gson();
 String jsonRepresentation = gson.toJson(objectToSerialize);
 System.out.println(jsonRepresentation);

 ===== OUTPUT =====
 {"name":"a","someOtherField":"b"}
 

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

Author:
Inderjeet Singh, Joel Leitch
See Also:
FieldNamingPolicy

Required Element Summary
 String value
           
 

Element Detail

value

public abstract String value
Returns:
the desired name of the field when it is serialized


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/annotations/Since.html000066400000000000000000000255111316034351600277060ustar00rootroot00000000000000 Since (Gson 2.3.1 API)

com.google.gson.annotations
Annotation Type Since


@Retention(value=RUNTIME)
@Target(value={FIELD,TYPE})
public @interface Since

An annotation that indicates the version number since a member or a type has been present. This annotation is useful to manage versioning of your Json classes for a web-service.

This annotation has no effect unless you build Gson with a GsonBuilder and invoke GsonBuilder.setVersion(double) method.

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

 public class User {
   private String firstName;
   private String lastName;
   @Since(1.0) private String emailAddress;
   @Since(1.0) private String password;
   @Since(1.1) private Address address;
 }
 

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

Author:
Inderjeet Singh, Joel Leitch

Required Element Summary
 double value
          the value indicating a version number since this member or type has been present.
 

Element Detail

value

public abstract double value
the value indicating a version number since this member or type has been present.



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/annotations/Until.html000066400000000000000000000256421316034351600277450ustar00rootroot00000000000000 Until (Gson 2.3.1 API)

com.google.gson.annotations
Annotation Type Until


@Retention(value=RUNTIME)
@Target(value={FIELD,TYPE})
public @interface Until

An annotation that indicates the version number until a member or a type should be present. Basically, if Gson is created with a version number that exceeds the value stored in the Until annotation then the field will be ignored from the JSON output. This annotation is useful to manage versioning of your JSON classes for a web-service.

This annotation has no effect unless you build Gson with a GsonBuilder and invoke GsonBuilder.setVersion(double) method.

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

 public class User {
   private String firstName;
   private String lastName;
   @Until(1.1) private String emailAddress;
   @Until(1.1) private String password;
 }
 

If you created Gson with new Gson(), the toJson() and fromJson() methods will use all the fields for serialization and deserialization. However, if you created Gson with Gson gson = new GsonBuilder().setVersion(1.2).create() then the toJson() and fromJson() methods of Gson will exclude the emailAddress and password fields from the example above, because the version number passed to the GsonBuilder, 1.2, exceeds the version number set on the Until annotation, 1.1, for those fields.

Since:
1.3
Author:
Inderjeet Singh, Joel Leitch

Required Element Summary
 double value
          the value indicating a version number until this member or type should be ignored.
 

Element Detail

value

public abstract double value
the value indicating a version number until this member or type should be ignored.



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/annotations/class-use/000077500000000000000000000000001316034351600276525ustar00rootroot00000000000000gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/annotations/class-use/Expose.html000066400000000000000000000137001316034351600320040ustar00rootroot00000000000000 Uses of Class com.google.gson.annotations.Expose (Gson 2.3.1 API)

Uses of Class
com.google.gson.annotations.Expose

No usage of com.google.gson.annotations.Expose



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/annotations/class-use/JsonAdapter.html000066400000000000000000000137621316034351600327630ustar00rootroot00000000000000 Uses of Class com.google.gson.annotations.JsonAdapter (Gson 2.3.1 API)

Uses of Class
com.google.gson.annotations.JsonAdapter

No usage of com.google.gson.annotations.JsonAdapter



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/annotations/class-use/SerializedName.html000066400000000000000000000140201316034351600334310ustar00rootroot00000000000000 Uses of Class com.google.gson.annotations.SerializedName (Gson 2.3.1 API)

Uses of Class
com.google.gson.annotations.SerializedName

No usage of com.google.gson.annotations.SerializedName



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/annotations/class-use/Since.html000066400000000000000000000136661316034351600316150ustar00rootroot00000000000000 Uses of Class com.google.gson.annotations.Since (Gson 2.3.1 API)

Uses of Class
com.google.gson.annotations.Since

No usage of com.google.gson.annotations.Since



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/annotations/class-use/Until.html000066400000000000000000000136661316034351600316470ustar00rootroot00000000000000 Uses of Class com.google.gson.annotations.Until (Gson 2.3.1 API)

Uses of Class
com.google.gson.annotations.Until

No usage of com.google.gson.annotations.Until



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/annotations/package-frame.html000066400000000000000000000026431316034351600313310ustar00rootroot00000000000000 com.google.gson.annotations (Gson 2.3.1 API) com.google.gson.annotations
Annotation Types 
Expose
JsonAdapter
SerializedName
Since
Until
gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/annotations/package-summary.html000066400000000000000000000205121316034351600317270ustar00rootroot00000000000000 com.google.gson.annotations (Gson 2.3.1 API)

Package com.google.gson.annotations

This package provides annotations that can be used with Gson.

See:
          Description

Annotation Types Summary
Expose An annotation that indicates this member should be exposed for JSON serialization or deserialization.
JsonAdapter An annotation that indicates the Gson TypeAdapter to use with a class or field.
SerializedName An annotation that indicates this member should be serialized to JSON with the provided name value as its field name.
Since An annotation that indicates the version number since a member or a type has been present.
Until An annotation that indicates the version number until a member or a type should be present.
 

Package com.google.gson.annotations Description

This package provides annotations that can be used with Gson.

Author:
Inderjeet Singh, Joel Leitch


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/annotations/package-tree.html000066400000000000000000000175171316034351600312040ustar00rootroot00000000000000 com.google.gson.annotations Class Hierarchy (Gson 2.3.1 API)

Hierarchy For Package com.google.gson.annotations

Package Hierarchies:
All Packages

Annotation Type Hierarchy



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/annotations/package-use.html000066400000000000000000000131651316034351600310340ustar00rootroot00000000000000 Uses of Package com.google.gson.annotations (Gson 2.3.1 API)

Uses of Package
com.google.gson.annotations

No usage of com.google.gson.annotations



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/class-use/000077500000000000000000000000001316034351600253155ustar00rootroot00000000000000gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/class-use/ExclusionStrategy.html000066400000000000000000000230041316034351600316760ustar00rootroot00000000000000 Uses of Interface com.google.gson.ExclusionStrategy (Gson 2.3.1 API)

Uses of Interface
com.google.gson.ExclusionStrategy

Packages that use ExclusionStrategy
com.google.gson This package provides the Gson class to convert Json to Java and vice-versa. 
 

Uses of ExclusionStrategy in com.google.gson
 

Methods in com.google.gson with parameters of type ExclusionStrategy
 GsonBuilder GsonBuilder.addDeserializationExclusionStrategy(ExclusionStrategy strategy)
          Configures Gson to apply the passed in exclusion strategy during deserialization.
 GsonBuilder GsonBuilder.addSerializationExclusionStrategy(ExclusionStrategy strategy)
          Configures Gson to apply the passed in exclusion strategy during serialization.
 GsonBuilder GsonBuilder.setExclusionStrategies(ExclusionStrategy... strategies)
          Configures Gson to apply a set of exclusion strategies during both serialization and deserialization.
 



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/class-use/FieldAttributes.html000066400000000000000000000174511316034351600313050ustar00rootroot00000000000000 Uses of Class com.google.gson.FieldAttributes (Gson 2.3.1 API)

Uses of Class
com.google.gson.FieldAttributes

Packages that use FieldAttributes
com.google.gson This package provides the Gson class to convert Json to Java and vice-versa. 
 

Uses of FieldAttributes in com.google.gson
 

Methods in com.google.gson with parameters of type FieldAttributes
 boolean ExclusionStrategy.shouldSkipField(FieldAttributes f)
           
 



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/class-use/FieldNamingPolicy.html000066400000000000000000000232441316034351600315450ustar00rootroot00000000000000 Uses of Class com.google.gson.FieldNamingPolicy (Gson 2.3.1 API)

Uses of Class
com.google.gson.FieldNamingPolicy

Packages that use FieldNamingPolicy
com.google.gson This package provides the Gson class to convert Json to Java and vice-versa. 
 

Uses of FieldNamingPolicy in com.google.gson
 

Methods in com.google.gson that return FieldNamingPolicy
static FieldNamingPolicy FieldNamingPolicy.valueOf(String name)
          Returns the enum constant of this type with the specified name.
static FieldNamingPolicy[] FieldNamingPolicy.values()
          Returns an array containing the constants of this enum type, in the order they are declared.
 

Methods in com.google.gson with parameters of type FieldNamingPolicy
 GsonBuilder GsonBuilder.setFieldNamingPolicy(FieldNamingPolicy namingConvention)
          Configures Gson to apply a specific naming policy to an object's field during serialization and deserialization.
 



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/class-use/FieldNamingStrategy.html000066400000000000000000000217341316034351600321120ustar00rootroot00000000000000 Uses of Interface com.google.gson.FieldNamingStrategy (Gson 2.3.1 API)

Uses of Interface
com.google.gson.FieldNamingStrategy

Packages that use FieldNamingStrategy
com.google.gson This package provides the Gson class to convert Json to Java and vice-versa. 
 

Uses of FieldNamingStrategy in com.google.gson
 

Classes in com.google.gson that implement FieldNamingStrategy
 class FieldNamingPolicy
          An enumeration that defines a few standard naming conventions for JSON field names.
 

Methods in com.google.gson with parameters of type FieldNamingStrategy
 GsonBuilder GsonBuilder.setFieldNamingStrategy(FieldNamingStrategy fieldNamingStrategy)
          Configures Gson to apply a specific naming policy strategy to an object's field during serialization and deserialization.
 



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/class-use/Gson.html000066400000000000000000000220761316034351600271200ustar00rootroot00000000000000 Uses of Class com.google.gson.Gson (Gson 2.3.1 API)

Uses of Class
com.google.gson.Gson

Packages that use Gson
com.google.gson This package provides the Gson class to convert Json to Java and vice-versa. 
 

Uses of Gson in com.google.gson
 

Methods in com.google.gson that return Gson
 Gson GsonBuilder.create()
          Creates a Gson instance based on the current configuration.
 

Methods in com.google.gson with parameters of type Gson
<T> TypeAdapter<T>
TypeAdapterFactory.create(Gson gson, TypeToken<T> type)
          Returns a type adapter for type, or null if this factory doesn't support type.
 



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/class-use/GsonBuilder.html000066400000000000000000000530731316034351600304300ustar00rootroot00000000000000 Uses of Class com.google.gson.GsonBuilder (Gson 2.3.1 API)

Uses of Class
com.google.gson.GsonBuilder

Packages that use GsonBuilder
com.google.gson This package provides the Gson class to convert Json to Java and vice-versa. 
 

Uses of GsonBuilder in com.google.gson
 

Methods in com.google.gson that return GsonBuilder
 GsonBuilder GsonBuilder.addDeserializationExclusionStrategy(ExclusionStrategy strategy)
          Configures Gson to apply the passed in exclusion strategy during deserialization.
 GsonBuilder GsonBuilder.addSerializationExclusionStrategy(ExclusionStrategy strategy)
          Configures Gson to apply the passed in exclusion strategy during serialization.
 GsonBuilder GsonBuilder.disableHtmlEscaping()
          By default, Gson escapes HTML characters such as < > etc.
 GsonBuilder GsonBuilder.disableInnerClassSerialization()
          Configures Gson to exclude inner classes during serialization.
 GsonBuilder GsonBuilder.enableComplexMapKeySerialization()
          Enabling this feature will only change the serialized form if the map key is a complex type (i.e.
 GsonBuilder GsonBuilder.excludeFieldsWithModifiers(int... modifiers)
          Configures Gson to excludes all class fields that have the specified modifiers.
 GsonBuilder GsonBuilder.excludeFieldsWithoutExposeAnnotation()
          Configures Gson to exclude all fields from consideration for serialization or deserialization that do not have the Expose annotation.
 GsonBuilder GsonBuilder.generateNonExecutableJson()
          Makes the output JSON non-executable in Javascript by prefixing the generated JSON with some special text.
 GsonBuilder GsonBuilder.registerTypeAdapter(Type type, Object typeAdapter)
          Configures Gson for custom serialization or deserialization.
 GsonBuilder GsonBuilder.registerTypeAdapterFactory(TypeAdapterFactory factory)
          Register a factory for type adapters.
 GsonBuilder GsonBuilder.registerTypeHierarchyAdapter(Class<?> baseType, Object typeAdapter)
          Configures Gson for custom serialization or deserialization for an inheritance type hierarchy.
 GsonBuilder GsonBuilder.serializeNulls()
          Configure Gson to serialize null fields.
 GsonBuilder GsonBuilder.serializeSpecialFloatingPointValues()
          Section 2.4 of JSON specification disallows special double values (NaN, Infinity, -Infinity).
 GsonBuilder GsonBuilder.setDateFormat(int style)
          Configures Gson to to serialize Date objects according to the style value provided.
 GsonBuilder GsonBuilder.setDateFormat(int dateStyle, int timeStyle)
          Configures Gson to to serialize Date objects according to the style value provided.
 GsonBuilder GsonBuilder.setDateFormat(String pattern)
          Configures Gson to serialize Date objects according to the pattern provided.
 GsonBuilder GsonBuilder.setExclusionStrategies(ExclusionStrategy... strategies)
          Configures Gson to apply a set of exclusion strategies during both serialization and deserialization.
 GsonBuilder GsonBuilder.setFieldNamingPolicy(FieldNamingPolicy namingConvention)
          Configures Gson to apply a specific naming policy to an object's field during serialization and deserialization.
 GsonBuilder GsonBuilder.setFieldNamingStrategy(FieldNamingStrategy fieldNamingStrategy)
          Configures Gson to apply a specific naming policy strategy to an object's field during serialization and deserialization.
 GsonBuilder GsonBuilder.setLongSerializationPolicy(LongSerializationPolicy serializationPolicy)
          Configures Gson to apply a specific serialization policy for Long and long objects.
 GsonBuilder GsonBuilder.setPrettyPrinting()
          Configures Gson to output Json that fits in a page for pretty printing.
 GsonBuilder GsonBuilder.setVersion(double ignoreVersionsAfter)
          Configures Gson to enable versioning support.
 



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/class-use/InstanceCreator.html000066400000000000000000000135711316034351600312760ustar00rootroot00000000000000 Uses of Interface com.google.gson.InstanceCreator (Gson 2.3.1 API)

Uses of Interface
com.google.gson.InstanceCreator

No usage of com.google.gson.InstanceCreator



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/class-use/JsonArray.html000066400000000000000000000225371316034351600301240ustar00rootroot00000000000000 Uses of Class com.google.gson.JsonArray (Gson 2.3.1 API)

Uses of Class
com.google.gson.JsonArray

Packages that use JsonArray
com.google.gson This package provides the Gson class to convert Json to Java and vice-versa. 
 

Uses of JsonArray in com.google.gson
 

Methods in com.google.gson that return JsonArray
 JsonArray JsonElement.getAsJsonArray()
          convenience method to get this element as a JsonArray.
 JsonArray JsonObject.getAsJsonArray(String memberName)
          Convenience method to get the specified member as a JsonArray.
 

Methods in com.google.gson with parameters of type JsonArray
 void JsonArray.addAll(JsonArray array)
          Adds all the elements of the specified array to self.
 



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/class-use/JsonDeserializationContext.html000066400000000000000000000211051316034351600335270ustar00rootroot00000000000000 Uses of Interface com.google.gson.JsonDeserializationContext (Gson 2.3.1 API)

Uses of Interface
com.google.gson.JsonDeserializationContext

Packages that use JsonDeserializationContext
com.google.gson This package provides the Gson class to convert Json to Java and vice-versa. 
 

Uses of JsonDeserializationContext in com.google.gson
 

Methods in com.google.gson with parameters of type JsonDeserializationContext
 T JsonDeserializer.deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
          Gson invokes this call-back method during deserialization when it encounters a field of the specified type.
 



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/class-use/JsonDeserializer.html000066400000000000000000000136031316034351600314620ustar00rootroot00000000000000 Uses of Interface com.google.gson.JsonDeserializer (Gson 2.3.1 API)

Uses of Interface
com.google.gson.JsonDeserializer

No usage of com.google.gson.JsonDeserializer



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/class-use/JsonElement.html000066400000000000000000001005251316034351600304310ustar00rootroot00000000000000 Uses of Class com.google.gson.JsonElement (Gson 2.3.1 API)

Uses of Class
com.google.gson.JsonElement

Packages that use JsonElement
com.google.gson This package provides the Gson class to convert Json to Java and vice-versa. 
 

Uses of JsonElement in com.google.gson
 

Subclasses of JsonElement in com.google.gson
 class JsonArray
          A class representing an array type in Json.
 class JsonNull
          A class representing a Json null value.
 class JsonObject
          A class representing an object type in Json.
 class JsonPrimitive
          A class representing a Json primitive value.
 

Methods in com.google.gson that return JsonElement
 JsonElement JsonArray.get(int i)
          Returns the ith element of the array.
 JsonElement JsonObject.get(String memberName)
          Returns the member with the specified name.
 JsonElement JsonStreamParser.next()
          Returns the next available JsonElement on the reader.
 JsonElement JsonParser.parse(JsonReader json)
          Returns the next value from the JSON stream as a parse tree.
 JsonElement JsonParser.parse(Reader json)
          Parses the specified JSON string into a parse tree
 JsonElement JsonParser.parse(String json)
          Parses the specified JSON string into a parse tree
 JsonElement JsonArray.remove(int index)
          Removes the element at the specified position in this array.
 JsonElement JsonObject.remove(String property)
          Removes the property from this JsonObject.
abstract  JsonElement LongSerializationPolicy.serialize(Long value)
          Serialize this value using this serialization policy.
 JsonElement JsonSerializationContext.serialize(Object src)
          Invokes default serialization on the specified object.
 JsonElement JsonSerializationContext.serialize(Object src, Type typeOfSrc)
          Invokes default serialization on the specified object passing the specific type information.
 JsonElement JsonSerializer.serialize(T src, Type typeOfSrc, JsonSerializationContext context)
          Gson invokes this call-back method during serialization when it encounters a field of the specified type.
 JsonElement JsonArray.set(int index, JsonElement element)
          Replaces the element at the specified position in this array with the specified element.
 JsonElement Gson.toJsonTree(Object src)
          This method serializes the specified object into its equivalent representation as a tree of JsonElements.
 JsonElement Gson.toJsonTree(Object src, Type typeOfSrc)
          This method serializes the specified object, including those of generic types, into its equivalent representation as a tree of JsonElements.
 JsonElement TypeAdapter.toJsonTree(T value)
          Converts value to a JSON tree.
 

Methods in com.google.gson that return types with arguments of type JsonElement
 Set<Map.Entry<String,JsonElement>> JsonObject.entrySet()
          Returns a set of members of this object.
 Iterator<JsonElement> JsonArray.iterator()
          Returns an iterator to navigate the elemetns of the array.
 

Methods in com.google.gson with parameters of type JsonElement
 void JsonArray.add(JsonElement element)
          Adds the specified element to self.
 void JsonObject.add(String property, JsonElement value)
          Adds a member, which is a name-value pair, to self.
 boolean JsonArray.contains(JsonElement element)
          Returns true if this array contains the specified element.
<T> T
JsonDeserializationContext.deserialize(JsonElement json, Type typeOfT)
          Invokes default deserialization on the specified object.
 T JsonDeserializer.deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
          Gson invokes this call-back method during deserialization when it encounters a field of the specified type.
<T> T
Gson.fromJson(JsonElement json, Class<T> classOfT)
          This method deserializes the Json read from the specified parse tree into an object of the specified type.
<T> T
Gson.fromJson(JsonElement json, Type typeOfT)
          This method deserializes the Json read from the specified parse tree into an object of the specified type.
 T TypeAdapter.fromJsonTree(JsonElement jsonTree)
          Converts jsonTree to a Java object.
 boolean JsonArray.remove(JsonElement element)
          Removes the first occurrence of the specified element from this array, if it is present.
 JsonElement JsonArray.set(int index, JsonElement element)
          Replaces the element at the specified position in this array with the specified element.
 String Gson.toJson(JsonElement jsonElement)
          Converts a tree of JsonElements into its equivalent JSON representation.
 void Gson.toJson(JsonElement jsonElement, Appendable writer)
          Writes out the equivalent JSON for a tree of JsonElements.
 void Gson.toJson(JsonElement jsonElement, JsonWriter writer)
          Writes the JSON for jsonElement to writer.
 



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/class-use/JsonIOException.html000066400000000000000000000370221316034351600312270ustar00rootroot00000000000000 Uses of Class com.google.gson.JsonIOException (Gson 2.3.1 API)

Uses of Class
com.google.gson.JsonIOException

Packages that use JsonIOException
com.google.gson This package provides the Gson class to convert Json to Java and vice-versa. 
 

Uses of JsonIOException in com.google.gson
 

Methods in com.google.gson that throw JsonIOException
<T> T
Gson.fromJson(JsonReader reader, Type typeOfT)
          Reads the next JSON value from reader and convert it to an object of type typeOfT.
<T> T
Gson.fromJson(Reader json, Class<T> classOfT)
          This method deserializes the Json read from the specified reader into an object of the specified class.
<T> T
Gson.fromJson(Reader json, Type typeOfT)
          This method deserializes the Json read from the specified reader into an object of the specified type.
 JsonElement JsonParser.parse(JsonReader json)
          Returns the next value from the JSON stream as a parse tree.
 JsonElement JsonParser.parse(Reader json)
          Parses the specified JSON string into a parse tree
 void Gson.toJson(JsonElement jsonElement, Appendable writer)
          Writes out the equivalent JSON for a tree of JsonElements.
 void Gson.toJson(JsonElement jsonElement, JsonWriter writer)
          Writes the JSON for jsonElement to writer.
 void Gson.toJson(Object src, Appendable writer)
          This method serializes the specified object into its equivalent Json representation.
 void Gson.toJson(Object src, Type typeOfSrc, Appendable writer)
          This method serializes the specified object, including those of generic types, into its equivalent Json representation.
 void Gson.toJson(Object src, Type typeOfSrc, JsonWriter writer)
          Writes the JSON representation of src of type typeOfSrc to writer.
 



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/class-use/JsonNull.html000066400000000000000000000211131316034351600277450ustar00rootroot00000000000000 Uses of Class com.google.gson.JsonNull (Gson 2.3.1 API)

Uses of Class
com.google.gson.JsonNull

Packages that use JsonNull
com.google.gson This package provides the Gson class to convert Json to Java and vice-versa. 
 

Uses of JsonNull in com.google.gson
 

Fields in com.google.gson declared as JsonNull
static JsonNull JsonNull.INSTANCE
          singleton for JsonNull
 

Methods in com.google.gson that return JsonNull
 JsonNull JsonElement.getAsJsonNull()
          convenience method to get this element as a JsonNull.
 



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/class-use/JsonObject.html000066400000000000000000000207301316034351600302450ustar00rootroot00000000000000 Uses of Class com.google.gson.JsonObject (Gson 2.3.1 API)

Uses of Class
com.google.gson.JsonObject

Packages that use JsonObject
com.google.gson This package provides the Gson class to convert Json to Java and vice-versa. 
 

Uses of JsonObject in com.google.gson
 

Methods in com.google.gson that return JsonObject
 JsonObject JsonElement.getAsJsonObject()
          convenience method to get this element as a JsonObject.
 JsonObject JsonObject.getAsJsonObject(String memberName)
          Convenience method to get the specified member as a JsonObject.
 



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/class-use/JsonParseException.html000066400000000000000000000262671316034351600320030ustar00rootroot00000000000000 Uses of Class com.google.gson.JsonParseException (Gson 2.3.1 API)

Uses of Class
com.google.gson.JsonParseException

Packages that use JsonParseException
com.google.gson This package provides the Gson class to convert Json to Java and vice-versa. 
 

Uses of JsonParseException in com.google.gson
 

Subclasses of JsonParseException in com.google.gson
 class JsonIOException
          This exception is raised when Gson was unable to read an input stream or write to one.
 class JsonSyntaxException
          This exception is raised when Gson attempts to read (or write) a malformed JSON element.
 

Methods in com.google.gson that throw JsonParseException
<T> T
JsonDeserializationContext.deserialize(JsonElement json, Type typeOfT)
          Invokes default deserialization on the specified object.
 T JsonDeserializer.deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
          Gson invokes this call-back method during deserialization when it encounters a field of the specified type.
 JsonElement JsonStreamParser.next()
          Returns the next available JsonElement on the reader.
 



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/class-use/JsonParser.html000066400000000000000000000134631316034351600303000ustar00rootroot00000000000000 Uses of Class com.google.gson.JsonParser (Gson 2.3.1 API)

Uses of Class
com.google.gson.JsonParser

No usage of com.google.gson.JsonParser



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/class-use/JsonPrimitive.html000066400000000000000000000210561316034351600310110ustar00rootroot00000000000000 Uses of Class com.google.gson.JsonPrimitive (Gson 2.3.1 API)

Uses of Class
com.google.gson.JsonPrimitive

Packages that use JsonPrimitive
com.google.gson This package provides the Gson class to convert Json to Java and vice-versa. 
 

Uses of JsonPrimitive in com.google.gson
 

Methods in com.google.gson that return JsonPrimitive
 JsonPrimitive JsonElement.getAsJsonPrimitive()
          convenience method to get this element as a JsonPrimitive.
 JsonPrimitive JsonObject.getAsJsonPrimitive(String memberName)
          Convenience method to get the specified member as a JsonPrimitive element.
 



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/class-use/JsonSerializationContext.html000066400000000000000000000207661316034351600332320ustar00rootroot00000000000000 Uses of Interface com.google.gson.JsonSerializationContext (Gson 2.3.1 API)

Uses of Interface
com.google.gson.JsonSerializationContext

Packages that use JsonSerializationContext
com.google.gson This package provides the Gson class to convert Json to Java and vice-versa. 
 

Uses of JsonSerializationContext in com.google.gson
 

Methods in com.google.gson with parameters of type JsonSerializationContext
 JsonElement JsonSerializer.serialize(T src, Type typeOfSrc, JsonSerializationContext context)
          Gson invokes this call-back method during serialization when it encounters a field of the specified type.
 



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/class-use/JsonSerializer.html000066400000000000000000000135571316034351600311610ustar00rootroot00000000000000 Uses of Interface com.google.gson.JsonSerializer (Gson 2.3.1 API)

Uses of Interface
com.google.gson.JsonSerializer

No usage of com.google.gson.JsonSerializer



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/class-use/JsonStreamParser.html000066400000000000000000000135571316034351600314600ustar00rootroot00000000000000 Uses of Class com.google.gson.JsonStreamParser (Gson 2.3.1 API)

Uses of Class
com.google.gson.JsonStreamParser

No usage of com.google.gson.JsonStreamParser



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/class-use/JsonSyntaxException.html000066400000000000000000000372711316034351600322140ustar00rootroot00000000000000 Uses of Class com.google.gson.JsonSyntaxException (Gson 2.3.1 API)

Uses of Class
com.google.gson.JsonSyntaxException

Packages that use JsonSyntaxException
com.google.gson This package provides the Gson class to convert Json to Java and vice-versa. 
 

Uses of JsonSyntaxException in com.google.gson
 

Methods in com.google.gson that throw JsonSyntaxException
<T> T
Gson.fromJson(JsonElement json, Class<T> classOfT)
          This method deserializes the Json read from the specified parse tree into an object of the specified type.
<T> T
Gson.fromJson(JsonElement json, Type typeOfT)
          This method deserializes the Json read from the specified parse tree into an object of the specified type.
<T> T
Gson.fromJson(JsonReader reader, Type typeOfT)
          Reads the next JSON value from reader and convert it to an object of type typeOfT.
<T> T
Gson.fromJson(Reader json, Class<T> classOfT)
          This method deserializes the Json read from the specified reader into an object of the specified class.
<T> T
Gson.fromJson(Reader json, Type typeOfT)
          This method deserializes the Json read from the specified reader into an object of the specified type.
<T> T
Gson.fromJson(String json, Class<T> classOfT)
          This method deserializes the specified Json into an object of the specified class.
<T> T
Gson.fromJson(String json, Type typeOfT)
          This method deserializes the specified Json into an object of the specified type.
 JsonElement JsonParser.parse(JsonReader json)
          Returns the next value from the JSON stream as a parse tree.
 JsonElement JsonParser.parse(Reader json)
          Parses the specified JSON string into a parse tree
 JsonElement JsonParser.parse(String json)
          Parses the specified JSON string into a parse tree
 



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/class-use/LongSerializationPolicy.html000066400000000000000000000235301316034351600330230ustar00rootroot00000000000000 Uses of Class com.google.gson.LongSerializationPolicy (Gson 2.3.1 API)

Uses of Class
com.google.gson.LongSerializationPolicy

Packages that use LongSerializationPolicy
com.google.gson This package provides the Gson class to convert Json to Java and vice-versa. 
 

Uses of LongSerializationPolicy in com.google.gson
 

Methods in com.google.gson that return LongSerializationPolicy
static LongSerializationPolicy LongSerializationPolicy.valueOf(String name)
          Returns the enum constant of this type with the specified name.
static LongSerializationPolicy[] LongSerializationPolicy.values()
          Returns an array containing the constants of this enum type, in the order they are declared.
 

Methods in com.google.gson with parameters of type LongSerializationPolicy
 GsonBuilder GsonBuilder.setLongSerializationPolicy(LongSerializationPolicy serializationPolicy)
          Configures Gson to apply a specific serialization policy for Long and long objects.
 



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/class-use/TypeAdapter.html000066400000000000000000000267031316034351600304350ustar00rootroot00000000000000 Uses of Class com.google.gson.TypeAdapter (Gson 2.3.1 API)

Uses of Class
com.google.gson.TypeAdapter

Packages that use TypeAdapter
com.google.gson This package provides the Gson class to convert Json to Java and vice-versa. 
 

Uses of TypeAdapter in com.google.gson
 

Methods in com.google.gson that return TypeAdapter
<T> TypeAdapter<T>
TypeAdapterFactory.create(Gson gson, TypeToken<T> type)
          Returns a type adapter for type, or null if this factory doesn't support type.
<T> TypeAdapter<T>
Gson.getAdapter(Class<T> type)
          Returns the type adapter for type.
<T> TypeAdapter<T>
Gson.getAdapter(TypeToken<T> type)
          Returns the type adapter for type.
<T> TypeAdapter<T>
Gson.getDelegateAdapter(TypeAdapterFactory skipPast, TypeToken<T> type)
          This method is used to get an alternate type adapter for the specified type.
 TypeAdapter<T> TypeAdapter.nullSafe()
          This wrapper method is used to make a type adapter null tolerant.
 



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/class-use/TypeAdapterFactory.html000066400000000000000000000220601316034351600317550ustar00rootroot00000000000000 Uses of Interface com.google.gson.TypeAdapterFactory (Gson 2.3.1 API)

Uses of Interface
com.google.gson.TypeAdapterFactory

Packages that use TypeAdapterFactory
com.google.gson This package provides the Gson class to convert Json to Java and vice-versa. 
 

Uses of TypeAdapterFactory in com.google.gson
 

Methods in com.google.gson with parameters of type TypeAdapterFactory
<T> TypeAdapter<T>
Gson.getDelegateAdapter(TypeAdapterFactory skipPast, TypeToken<T> type)
          This method is used to get an alternate type adapter for the specified type.
 GsonBuilder GsonBuilder.registerTypeAdapterFactory(TypeAdapterFactory factory)
          Register a factory for type adapters.
 



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/package-frame.html000066400000000000000000000077521316034351600270020ustar00rootroot00000000000000 com.google.gson (Gson 2.3.1 API) com.google.gson
Interfaces 
ExclusionStrategy
FieldNamingStrategy
InstanceCreator
JsonDeserializationContext
JsonDeserializer
JsonSerializationContext
JsonSerializer
TypeAdapterFactory
Classes 
FieldAttributes
Gson
GsonBuilder
JsonArray
JsonElement
JsonNull
JsonObject
JsonParser
JsonPrimitive
JsonStreamParser
TypeAdapter
Enums 
FieldNamingPolicy
LongSerializationPolicy
Exceptions 
JsonIOException
JsonParseException
JsonSyntaxException
gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/package-summary.html000066400000000000000000000352741316034351600274050ustar00rootroot00000000000000 com.google.gson (Gson 2.3.1 API)

Package com.google.gson

This package provides the Gson class to convert Json to Java and vice-versa.

See:
          Description

Interface Summary
ExclusionStrategy A strategy (or policy) definition that is used to decide whether or not a field or top-level class should be serialized or deserialized as part of the JSON output/input.
FieldNamingStrategy A mechanism for providing custom field naming in Gson.
InstanceCreator<T> This interface is implemented to create instances of a class that does not define a no-args constructor.
JsonDeserializationContext Context for deserialization that is passed to a custom deserializer during invocation of its JsonDeserializer.deserialize(JsonElement, Type, JsonDeserializationContext) method.
JsonDeserializer<T> Interface representing a custom deserializer for Json.
JsonSerializationContext Context for serialization that is passed to a custom serializer during invocation of its JsonSerializer.serialize(Object, Type, JsonSerializationContext) method.
JsonSerializer<T> Interface representing a custom serializer for Json.
TypeAdapterFactory Creates type adapters for set of related types.
 

Class Summary
FieldAttributes A data object that stores attributes of a field.
Gson This is the main class for using Gson.
GsonBuilder Use this builder to construct a Gson instance when you need to set configuration options other than the default.
JsonArray A class representing an array type in Json.
JsonElement A class representing an element of Json.
JsonNull A class representing a Json null value.
JsonObject A class representing an object type in Json.
JsonParser A parser to parse Json into a parse tree of JsonElements
JsonPrimitive A class representing a Json primitive value.
JsonStreamParser A streaming parser that allows reading of multiple JsonElements from the specified reader asynchronously.
TypeAdapter<T> Converts Java objects to and from JSON.
 

Enum Summary
FieldNamingPolicy An enumeration that defines a few standard naming conventions for JSON field names.
LongSerializationPolicy Defines the expected format for a long or Long type when its serialized.
 

Exception Summary
JsonIOException This exception is raised when Gson was unable to read an input stream or write to one.
JsonParseException This exception is raised if there is a serious issue that occurs during parsing of a Json string.
JsonSyntaxException This exception is raised when Gson attempts to read (or write) a malformed JSON element.
 

Package com.google.gson Description

This package provides the Gson class to convert Json to Java and vice-versa.

The primary class to use is Gson which can be constructed with new Gson() (using default settings) or by using GsonBuilder (to configure various options such as using versioning and so on).

Author:
Inderjeet Singh, Joel Leitch


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/package-tree.html000066400000000000000000000267761316034351600266560ustar00rootroot00000000000000 com.google.gson Class Hierarchy (Gson 2.3.1 API)

Hierarchy For Package com.google.gson

Package Hierarchies:
All Packages

Class Hierarchy

Interface Hierarchy

Enum Hierarchy



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/package-use.html000066400000000000000000000315521316034351600264770ustar00rootroot00000000000000 Uses of Package com.google.gson (Gson 2.3.1 API)

Uses of Package
com.google.gson

Packages that use com.google.gson
com.google.gson This package provides the Gson class to convert Json to Java and vice-versa. 
 

Classes in com.google.gson used by com.google.gson
ExclusionStrategy
          A strategy (or policy) definition that is used to decide whether or not a field or top-level class should be serialized or deserialized as part of the JSON output/input.
FieldAttributes
          A data object that stores attributes of a field.
FieldNamingPolicy
          An enumeration that defines a few standard naming conventions for JSON field names.
FieldNamingStrategy
          A mechanism for providing custom field naming in Gson.
Gson
          This is the main class for using Gson.
GsonBuilder
          Use this builder to construct a Gson instance when you need to set configuration options other than the default.
JsonArray
          A class representing an array type in Json.
JsonDeserializationContext
          Context for deserialization that is passed to a custom deserializer during invocation of its JsonDeserializer.deserialize(JsonElement, Type, JsonDeserializationContext) method.
JsonElement
          A class representing an element of Json.
JsonIOException
          This exception is raised when Gson was unable to read an input stream or write to one.
JsonNull
          A class representing a Json null value.
JsonObject
          A class representing an object type in Json.
JsonParseException
          This exception is raised if there is a serious issue that occurs during parsing of a Json string.
JsonPrimitive
          A class representing a Json primitive value.
JsonSerializationContext
          Context for serialization that is passed to a custom serializer during invocation of its JsonSerializer.serialize(Object, Type, JsonSerializationContext) method.
JsonSyntaxException
          This exception is raised when Gson attempts to read (or write) a malformed JSON element.
LongSerializationPolicy
          Defines the expected format for a long or Long type when its serialized.
TypeAdapter
          Converts Java objects to and from JSON.
TypeAdapterFactory
          Creates type adapters for set of related types.
 



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/reflect/000077500000000000000000000000001316034351600250425ustar00rootroot00000000000000gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/reflect/TypeToken.html000066400000000000000000000554371316034351600276700ustar00rootroot00000000000000 TypeToken (Gson 2.3.1 API)

com.google.gson.reflect
Class TypeToken<T>

java.lang.Object
  extended by com.google.gson.reflect.TypeToken<T>

public class TypeToken<T>
extends Object

Represents a generic type T. Java doesn't yet provide a way to represent generic types, so this class does. Forces clients to create a subclass of this class which enables retrieval the type information even at runtime.

For example, to create a type literal for List<String>, you can create an empty anonymous inner class:

TypeToken<List<String>> list = new TypeToken<List<String>>() {};

This syntax cannot be used to create type literals that have wildcard parameters, such as Class<?> or List<? extends CharSequence>.

Author:
Bob Lee, Sven Mawson, Jesse Wilson

Constructor Summary
protected TypeToken()
          Constructs a new type literal.
 
Method Summary
 boolean equals(Object o)
           
static
<T> TypeToken<T>
get(Class<T> type)
          Gets type literal for the given Class instance.
static TypeToken<?> get(Type type)
          Gets type literal for the given Type instance.
 Class<? super T> getRawType()
          Returns the raw (non-generic) type for this type.
 Type getType()
          Gets underlying Type instance.
 int hashCode()
           
 boolean isAssignableFrom(Class<?> cls)
          Deprecated. this implementation may be inconsistent with javac for types with wildcards.
 boolean isAssignableFrom(Type from)
          Deprecated. this implementation may be inconsistent with javac for types with wildcards.
 boolean isAssignableFrom(TypeToken<?> token)
          Deprecated. this implementation may be inconsistent with javac for types with wildcards.
 String toString()
           
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Constructor Detail

TypeToken

protected TypeToken()
Constructs a new type literal. Derives represented class from type parameter.

Clients create an empty anonymous subclass. Doing so embeds the type parameter in the anonymous class's type hierarchy so we can reconstitute it at runtime despite erasure.

Method Detail

getRawType

public final Class<? super T> getRawType()
Returns the raw (non-generic) type for this type.


getType

public final Type getType()
Gets underlying Type instance.


isAssignableFrom

@Deprecated
public boolean isAssignableFrom(Class<?> cls)
Deprecated. this implementation may be inconsistent with javac for types with wildcards.

Check if this type is assignable from the given class object.


isAssignableFrom

@Deprecated
public boolean isAssignableFrom(Type from)
Deprecated. this implementation may be inconsistent with javac for types with wildcards.

Check if this type is assignable from the given Type.


isAssignableFrom

@Deprecated
public boolean isAssignableFrom(TypeToken<?> token)
Deprecated. this implementation may be inconsistent with javac for types with wildcards.

Check if this type is assignable from the given type token.


hashCode

public final int hashCode()
Overrides:
hashCode in class Object

equals

public final boolean equals(Object o)
Overrides:
equals in class Object

toString

public final String toString()
Overrides:
toString in class Object

get

public static TypeToken<?> get(Type type)
Gets type literal for the given Type instance.


get

public static <T> TypeToken<T> get(Class<T> type)
Gets type literal for the given Class instance.



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/reflect/class-use/000077500000000000000000000000001316034351600267415ustar00rootroot00000000000000gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/reflect/class-use/TypeToken.html000066400000000000000000000337411316034351600315610ustar00rootroot00000000000000 Uses of Class com.google.gson.reflect.TypeToken (Gson 2.3.1 API)

Uses of Class
com.google.gson.reflect.TypeToken

Packages that use TypeToken
com.google.gson This package provides the Gson class to convert Json to Java and vice-versa. 
com.google.gson.reflect This package provides utility classes for finding type information for generic types. 
 

Uses of TypeToken in com.google.gson
 

Methods in com.google.gson with parameters of type TypeToken
<T> TypeAdapter<T>
TypeAdapterFactory.create(Gson gson, TypeToken<T> type)
          Returns a type adapter for type, or null if this factory doesn't support type.
<T> TypeAdapter<T>
Gson.getAdapter(TypeToken<T> type)
          Returns the type adapter for type.
<T> TypeAdapter<T>
Gson.getDelegateAdapter(TypeAdapterFactory skipPast, TypeToken<T> type)
          This method is used to get an alternate type adapter for the specified type.
 

Uses of TypeToken in com.google.gson.reflect
 

Methods in com.google.gson.reflect that return TypeToken
static
<T> TypeToken<T>
TypeToken.get(Class<T> type)
          Gets type literal for the given Class instance.
static TypeToken<?> TypeToken.get(Type type)
          Gets type literal for the given Type instance.
 

Methods in com.google.gson.reflect with parameters of type TypeToken
 boolean TypeToken.isAssignableFrom(TypeToken<?> token)
          Deprecated. this implementation may be inconsistent with javac for types with wildcards.
 



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/reflect/package-frame.html000066400000000000000000000017051316034351600304160ustar00rootroot00000000000000 com.google.gson.reflect (Gson 2.3.1 API) com.google.gson.reflect
Classes 
TypeToken
gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/reflect/package-summary.html000066400000000000000000000154541316034351600310270ustar00rootroot00000000000000 com.google.gson.reflect (Gson 2.3.1 API)

Package com.google.gson.reflect

This package provides utility classes for finding type information for generic types.

See:
          Description

Class Summary
TypeToken<T> Represents a generic type T.
 

Package com.google.gson.reflect Description

This package provides utility classes for finding type information for generic types.

Author:
Inderjeet Singh, Joel Leitch


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/reflect/package-tree.html000066400000000000000000000144271316034351600302700ustar00rootroot00000000000000 com.google.gson.reflect Class Hierarchy (Gson 2.3.1 API)

Hierarchy For Package com.google.gson.reflect

Package Hierarchies:
All Packages

Class Hierarchy



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/reflect/package-use.html000066400000000000000000000175151316034351600301260ustar00rootroot00000000000000 Uses of Package com.google.gson.reflect (Gson 2.3.1 API)

Uses of Package
com.google.gson.reflect

Packages that use com.google.gson.reflect
com.google.gson This package provides the Gson class to convert Json to Java and vice-versa. 
com.google.gson.reflect This package provides utility classes for finding type information for generic types. 
 

Classes in com.google.gson.reflect used by com.google.gson
TypeToken
          Represents a generic type T.
 

Classes in com.google.gson.reflect used by com.google.gson.reflect
TypeToken
          Represents a generic type T.
 



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/stream/000077500000000000000000000000001316034351600247115ustar00rootroot00000000000000gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/stream/JsonReader.html000066400000000000000000001274631316034351600276500ustar00rootroot00000000000000 JsonReader (Gson 2.3.1 API)

com.google.gson.stream
Class JsonReader

java.lang.Object
  extended by com.google.gson.stream.JsonReader
All Implemented Interfaces:
Closeable

public class JsonReader
extends Object
implements Closeable

Reads a JSON (RFC 4627) encoded value as a stream of tokens. This stream includes both literal values (strings, numbers, booleans, and nulls) as well as the begin and end delimiters of objects and arrays. The tokens are traversed in depth-first order, the same order that they appear in the JSON document. Within JSON objects, name/value pairs are represented by a single token.

Parsing JSON

To create a recursive descent parser for your own JSON streams, first create an entry point method that creates a JsonReader.

Next, create handler methods for each structure in your JSON text. You'll need a method for each object type and for each array type.

  • Within array handling methods, first call beginArray() to consume the array's opening bracket. Then create a while loop that accumulates values, terminating when hasNext() is false. Finally, read the array's closing bracket by calling endArray().
  • Within object handling methods, first call beginObject() to consume the object's opening brace. Then create a while loop that assigns values to local variables based on their name. This loop should terminate when hasNext() is false. Finally, read the object's closing brace by calling endObject().

When a nested object or array is encountered, delegate to the corresponding handler method.

When an unknown name is encountered, strict parsers should fail with an exception. Lenient parsers should call skipValue() to recursively skip the value's nested tokens, which may otherwise conflict.

If a value may be null, you should first check using peek(). Null literals can be consumed using either nextNull() or skipValue().

Example

Suppose we'd like to parse a stream of messages such as the following:
 [
   {
     "id": 912345678901,
     "text": "How do I read a JSON stream in Java?",
     "geo": null,
     "user": {
       "name": "json_newb",
       "followers_count": 41
      }
   },
   {
     "id": 912345678902,
     "text": "@json_newb just use JsonReader!",
     "geo": [50.454722, -104.606667],
     "user": {
       "name": "jesse",
       "followers_count": 2
     }
   }
 ]
This code implements the parser for the above structure:
   public List<Message> readJsonStream(InputStream in) throws IOException {
     JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
     try {
       return readMessagesArray(reader);
     } finally {
       reader.close();
     }
   }

   public List<Message> readMessagesArray(JsonReader reader) throws IOException {
     List<Message> messages = new ArrayList<Message>();

     reader.beginArray();
     while (reader.hasNext()) {
       messages.add(readMessage(reader));
     }
     reader.endArray();
     return messages;
   }

   public Message readMessage(JsonReader reader) throws IOException {
     long id = -1;
     String text = null;
     User user = null;
     List<Double> geo = null;

     reader.beginObject();
     while (reader.hasNext()) {
       String name = reader.nextName();
       if (name.equals("id")) {
         id = reader.nextLong();
       } else if (name.equals("text")) {
         text = reader.nextString();
       } else if (name.equals("geo") && reader.peek() != JsonToken.NULL) {
         geo = readDoublesArray(reader);
       } else if (name.equals("user")) {
         user = readUser(reader);
       } else {
         reader.skipValue();
       }
     }
     reader.endObject();
     return new Message(id, text, user, geo);
   }

   public List<Double> readDoublesArray(JsonReader reader) throws IOException {
     List<Double> doubles = new ArrayList<Double>();

     reader.beginArray();
     while (reader.hasNext()) {
       doubles.add(reader.nextDouble());
     }
     reader.endArray();
     return doubles;
   }

   public User readUser(JsonReader reader) throws IOException {
     String username = null;
     int followersCount = -1;

     reader.beginObject();
     while (reader.hasNext()) {
       String name = reader.nextName();
       if (name.equals("name")) {
         username = reader.nextString();
       } else if (name.equals("followers_count")) {
         followersCount = reader.nextInt();
       } else {
         reader.skipValue();
       }
     }
     reader.endObject();
     return new User(username, followersCount);
   }

Number Handling

This reader permits numeric values to be read as strings and string values to be read as numbers. For example, both elements of the JSON array [1, "1"] may be read using either nextInt() or nextString(). This behavior is intended to prevent lossy numeric conversions: double is JavaScript's only numeric type and very large values like 9007199254740993 cannot be represented exactly on that platform. To minimize precision loss, extremely large values should be written and read as strings in JSON.

Non-Execute Prefix

Web servers that serve private data using JSON may be vulnerable to
Cross-site request forgery attacks. In such an attack, a malicious site gains access to a private JSON file by executing it with an HTML <script> tag.

Prefixing JSON files with ")]}'\n" makes them non-executable by <script> tags, disarming the attack. Since the prefix is malformed JSON, strict parsing fails when it is encountered. This class permits the non-execute prefix when lenient parsing is enabled.

Each JsonReader may be used to read a single JSON stream. Instances of this class are not thread safe.

Since:
1.6
Author:
Jesse Wilson

Constructor Summary
JsonReader(Reader in)
          Creates a new instance that reads a JSON-encoded stream from in.
 
Method Summary
 void beginArray()
          Consumes the next token from the JSON stream and asserts that it is the beginning of a new array.
 void beginObject()
          Consumes the next token from the JSON stream and asserts that it is the beginning of a new object.
 void close()
          Closes this JSON reader and the underlying Reader.
 void endArray()
          Consumes the next token from the JSON stream and asserts that it is the end of the current array.
 void endObject()
          Consumes the next token from the JSON stream and asserts that it is the end of the current object.
 String getPath()
          Returns a JsonPath to the current location in the JSON value.
 boolean hasNext()
          Returns true if the current array or object has another element.
 boolean isLenient()
          Returns true if this parser is liberal in what it accepts.
 boolean nextBoolean()
          Returns the boolean value of the next token, consuming it.
 double nextDouble()
          Returns the double value of the next token, consuming it.
 int nextInt()
          Returns the int value of the next token, consuming it.
 long nextLong()
          Returns the long value of the next token, consuming it.
 String nextName()
          Returns the next token, a property name, and consumes it.
 void nextNull()
          Consumes the next token from the JSON stream and asserts that it is a literal null.
 String nextString()
          Returns the string value of the next token, consuming it.
 JsonToken peek()
          Returns the type of the next token without consuming it.
 void setLenient(boolean lenient)
          Configure this parser to be be liberal in what it accepts.
 void skipValue()
          Skips the next value recursively.
 String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

JsonReader

public JsonReader(Reader in)
Creates a new instance that reads a JSON-encoded stream from in.

Method Detail

setLenient

public final void setLenient(boolean lenient)
Configure this parser to be be liberal in what it accepts. By default, this parser is strict and only accepts JSON as specified by RFC 4627. Setting the parser to lenient causes it to ignore the following syntax errors:
  • Streams that start with the non-execute prefix, ")]}'\n".
  • Streams that include multiple top-level values. With strict parsing, each stream must contain exactly one top-level value.
  • Top-level values of any type. With strict parsing, the top-level value must be an object or an array.
  • Numbers may be NaNs or infinities.
  • End of line comments starting with // or # and ending with a newline character.
  • C-style comments starting with /* and ending with */. Such comments may not be nested.
  • Names that are unquoted or 'single quoted'.
  • Strings that are unquoted or 'single quoted'.
  • Array elements separated by ; instead of ,.
  • Unnecessary array separators. These are interpreted as if null was the omitted value.
  • Names and values separated by = or => instead of :.
  • Name/value pairs separated by ; instead of ,.


isLenient

public final boolean isLenient()
Returns true if this parser is liberal in what it accepts.


beginArray

public void beginArray()
                throws IOException
Consumes the next token from the JSON stream and asserts that it is the beginning of a new array.

Throws:
IOException

endArray

public void endArray()
              throws IOException
Consumes the next token from the JSON stream and asserts that it is the end of the current array.

Throws:
IOException

beginObject

public void beginObject()
                 throws IOException
Consumes the next token from the JSON stream and asserts that it is the beginning of a new object.

Throws:
IOException

endObject

public void endObject()
               throws IOException
Consumes the next token from the JSON stream and asserts that it is the end of the current object.

Throws:
IOException

hasNext

public boolean hasNext()
                throws IOException
Returns true if the current array or object has another element.

Throws:
IOException

peek

public JsonToken peek()
               throws IOException
Returns the type of the next token without consuming it.

Throws:
IOException

nextName

public String nextName()
                throws IOException
Returns the next token, a property name, and consumes it.

Throws:
IOException - if the next token in the stream is not a property name.

nextString

public String nextString()
                  throws IOException
Returns the string value of the next token, consuming it. If the next token is a number, this method will return its string form.

Throws:
IllegalStateException - if the next token is not a string or if this reader is closed.
IOException

nextBoolean

public boolean nextBoolean()
                    throws IOException
Returns the boolean value of the next token, consuming it.

Throws:
IllegalStateException - if the next token is not a boolean or if this reader is closed.
IOException

nextNull

public void nextNull()
              throws IOException
Consumes the next token from the JSON stream and asserts that it is a literal null.

Throws:
IllegalStateException - if the next token is not null or if this reader is closed.
IOException

nextDouble

public double nextDouble()
                  throws IOException
Returns the double value of the next token, consuming it. If the next token is a string, this method will attempt to parse it as a double using Double.parseDouble(String).

Throws:
IllegalStateException - if the next token is not a literal value.
NumberFormatException - if the next literal value cannot be parsed as a double, or is non-finite.
IOException

nextLong

public long nextLong()
              throws IOException
Returns the long value of the next token, consuming it. If the next token is a string, this method will attempt to parse it as a long. If the next token's numeric value cannot be exactly represented by a Java long, this method throws.

Throws:
IllegalStateException - if the next token is not a literal value.
NumberFormatException - if the next literal value cannot be parsed as a number, or exactly represented as a long.
IOException

nextInt

public int nextInt()
            throws IOException
Returns the int value of the next token, consuming it. If the next token is a string, this method will attempt to parse it as an int. If the next token's numeric value cannot be exactly represented by a Java int, this method throws.

Throws:
IllegalStateException - if the next token is not a literal value.
NumberFormatException - if the next literal value cannot be parsed as a number, or exactly represented as an int.
IOException

close

public void close()
           throws IOException
Closes this JSON reader and the underlying Reader.

Specified by:
close in interface Closeable
Throws:
IOException

skipValue

public void skipValue()
               throws IOException
Skips the next value recursively. If it is an object or array, all nested elements are skipped. This method is intended for use when the JSON token stream contains unrecognized or unhandled values.

Throws:
IOException

toString

public String toString()
Overrides:
toString in class Object

getPath

public String getPath()
Returns a JsonPath to the current location in the JSON value.



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/stream/JsonToken.html000066400000000000000000000562151316034351600275220ustar00rootroot00000000000000 JsonToken (Gson 2.3.1 API)

com.google.gson.stream
Enum JsonToken

java.lang.Object
  extended by java.lang.Enum<JsonToken>
      extended by com.google.gson.stream.JsonToken
All Implemented Interfaces:
Serializable, Comparable<JsonToken>

public enum JsonToken
extends Enum<JsonToken>

A structure, name or value type in a JSON-encoded string.

Since:
1.6
Author:
Jesse Wilson

Enum Constant Summary
BEGIN_ARRAY
          The opening of a JSON array.
BEGIN_OBJECT
          The opening of a JSON object.
BOOLEAN
          A JSON true or false.
END_ARRAY
          The closing of a JSON array.
END_DOCUMENT
          The end of the JSON stream.
END_OBJECT
          The closing of a JSON object.
NAME
          A JSON property name.
NULL
          A JSON null.
NUMBER
          A JSON number represented in this API by a Java double, long, or int.
STRING
          A JSON string.
 
Method Summary
static JsonToken valueOf(String name)
          Returns the enum constant of this type with the specified name.
static JsonToken[] values()
          Returns an array containing the constants of this enum type, in the order they are declared.
 
Methods inherited from class java.lang.Enum
clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf
 
Methods inherited from class java.lang.Object
getClass, notify, notifyAll, wait, wait, wait
 

Enum Constant Detail

BEGIN_ARRAY

public static final JsonToken BEGIN_ARRAY
The opening of a JSON array. Written using JsonWriter.beginArray() and read using JsonReader.beginArray().


END_ARRAY

public static final JsonToken END_ARRAY
The closing of a JSON array. Written using JsonWriter.endArray() and read using JsonReader.endArray().


BEGIN_OBJECT

public static final JsonToken BEGIN_OBJECT
The opening of a JSON object. Written using JsonWriter.beginObject() and read using JsonReader.beginObject().


END_OBJECT

public static final JsonToken END_OBJECT
The closing of a JSON object. Written using JsonWriter.endObject() and read using JsonReader.endObject().


NAME

public static final JsonToken NAME
A JSON property name. Within objects, tokens alternate between names and their values. Written using JsonWriter.name(java.lang.String) and read using JsonReader.nextName()


STRING

public static final JsonToken STRING
A JSON string.


NUMBER

public static final JsonToken NUMBER
A JSON number represented in this API by a Java double, long, or int.


BOOLEAN

public static final JsonToken BOOLEAN
A JSON true or false.


NULL

public static final JsonToken NULL
A JSON null.


END_DOCUMENT

public static final JsonToken END_DOCUMENT
The end of the JSON stream. This sentinel value is returned by JsonReader.peek() to signal that the JSON-encoded value has no more tokens.

Method Detail

values

public static JsonToken[] values()
Returns an array containing the constants of this enum type, in the order they are declared. This method may be used to iterate over the constants as follows:
for (JsonToken c : JsonToken.values())
    System.out.println(c);

Returns:
an array containing the constants of this enum type, in the order they are declared

valueOf

public static JsonToken valueOf(String name)
Returns the enum constant of this type with the specified name. The string must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)

Parameters:
name - the name of the enum constant to be returned.
Returns:
the enum constant with the specified name
Throws:
IllegalArgumentException - if this enum type has no constant with the specified name
NullPointerException - if the argument is null


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/stream/JsonWriter.html000066400000000000000000001227141316034351600277140ustar00rootroot00000000000000 JsonWriter (Gson 2.3.1 API)

com.google.gson.stream
Class JsonWriter

java.lang.Object
  extended by com.google.gson.stream.JsonWriter
All Implemented Interfaces:
Closeable, Flushable

public class JsonWriter
extends Object
implements Closeable, Flushable

Writes a JSON (RFC 4627) encoded value to a stream, one token at a time. The stream includes both literal values (strings, numbers, booleans and nulls) as well as the begin and end delimiters of objects and arrays.

Encoding JSON

To encode your data as JSON, create a new JsonWriter. Each JSON document must contain one top-level array or object. Call methods on the writer as you walk the structure's contents, nesting arrays and objects as necessary:

Example

Suppose we'd like to encode a stream of messages such as the following:
 [
   {
     "id": 912345678901,
     "text": "How do I stream JSON in Java?",
     "geo": null,
     "user": {
       "name": "json_newb",
       "followers_count": 41
      }
   },
   {
     "id": 912345678902,
     "text": "@json_newb just use JsonWriter!",
     "geo": [50.454722, -104.606667],
     "user": {
       "name": "jesse",
       "followers_count": 2
     }
   }
 ]
This code encodes the above structure:
   public void writeJsonStream(OutputStream out, List<Message> messages) throws IOException {
     JsonWriter writer = new JsonWriter(new OutputStreamWriter(out, "UTF-8"));
     writer.setIndentSpaces(4);
     writeMessagesArray(writer, messages);
     writer.close();
   }

   public void writeMessagesArray(JsonWriter writer, List<Message> messages) throws IOException {
     writer.beginArray();
     for (Message message : messages) {
       writeMessage(writer, message);
     }
     writer.endArray();
   }

   public void writeMessage(JsonWriter writer, Message message) throws IOException {
     writer.beginObject();
     writer.name("id").value(message.getId());
     writer.name("text").value(message.getText());
     if (message.getGeo() != null) {
       writer.name("geo");
       writeDoublesArray(writer, message.getGeo());
     } else {
       writer.name("geo").nullValue();
     }
     writer.name("user");
     writeUser(writer, message.getUser());
     writer.endObject();
   }

   public void writeUser(JsonWriter writer, User user) throws IOException {
     writer.beginObject();
     writer.name("name").value(user.getName());
     writer.name("followers_count").value(user.getFollowersCount());
     writer.endObject();
   }

   public void writeDoublesArray(JsonWriter writer, List<Double> doubles) throws IOException {
     writer.beginArray();
     for (Double value : doubles) {
       writer.value(value);
     }
     writer.endArray();
   }

Each JsonWriter may be used to write a single JSON stream. Instances of this class are not thread safe. Calls that would result in a malformed JSON string will fail with an IllegalStateException.

Since:
1.6
Author:
Jesse Wilson

Constructor Summary
JsonWriter(Writer out)
          Creates a new instance that writes a JSON-encoded stream to out.
 
Method Summary
 JsonWriter beginArray()
          Begins encoding a new array.
 JsonWriter beginObject()
          Begins encoding a new object.
 void close()
          Flushes and closes this writer and the underlying Writer.
 JsonWriter endArray()
          Ends encoding the current array.
 JsonWriter endObject()
          Ends encoding the current object.
 void flush()
          Ensures all buffered data is written to the underlying Writer and flushes that writer.
 boolean getSerializeNulls()
          Returns true if object members are serialized when their value is null.
 boolean isHtmlSafe()
          Returns true if this writer writes JSON that's safe for inclusion in HTML and XML documents.
 boolean isLenient()
          Returns true if this writer has relaxed syntax rules.
 JsonWriter name(String name)
          Encodes the property name.
 JsonWriter nullValue()
          Encodes null.
 void setHtmlSafe(boolean htmlSafe)
          Configure this writer to emit JSON that's safe for direct inclusion in HTML and XML documents.
 void setIndent(String indent)
          Sets the indentation string to be repeated for each level of indentation in the encoded document.
 void setLenient(boolean lenient)
          Configure this writer to relax its syntax rules.
 void setSerializeNulls(boolean serializeNulls)
          Sets whether object members are serialized when their value is null.
 JsonWriter value(boolean value)
          Encodes value.
 JsonWriter value(double value)
          Encodes value.
 JsonWriter value(long value)
          Encodes value.
 JsonWriter value(Number value)
          Encodes value.
 JsonWriter value(String value)
          Encodes value.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

JsonWriter

public JsonWriter(Writer out)
Creates a new instance that writes a JSON-encoded stream to out. For best performance, ensure Writer is buffered; wrapping in BufferedWriter if necessary.

Method Detail

setIndent

public final void setIndent(String indent)
Sets the indentation string to be repeated for each level of indentation in the encoded document. If indent.isEmpty() the encoded document will be compact. Otherwise the encoded document will be more human-readable.

Parameters:
indent - a string containing only whitespace.

setLenient

public final void setLenient(boolean lenient)
Configure this writer to relax its syntax rules. By default, this writer only emits well-formed JSON as specified by RFC 4627. Setting the writer to lenient permits the following:
  • Top-level values of any type. With strict writing, the top-level value must be an object or an array.
  • Numbers may be NaNs or infinities.


isLenient

public boolean isLenient()
Returns true if this writer has relaxed syntax rules.


setHtmlSafe

public final void setHtmlSafe(boolean htmlSafe)
Configure this writer to emit JSON that's safe for direct inclusion in HTML and XML documents. This escapes the HTML characters <, >, & and = before writing them to the stream. Without this setting, your XML/HTML encoder should replace these characters with the corresponding escape sequences.


isHtmlSafe

public final boolean isHtmlSafe()
Returns true if this writer writes JSON that's safe for inclusion in HTML and XML documents.


setSerializeNulls

public final void setSerializeNulls(boolean serializeNulls)
Sets whether object members are serialized when their value is null. This has no impact on array elements. The default is true.


getSerializeNulls

public final boolean getSerializeNulls()
Returns true if object members are serialized when their value is null. This has no impact on array elements. The default is true.


beginArray

public JsonWriter beginArray()
                      throws IOException
Begins encoding a new array. Each call to this method must be paired with a call to endArray().

Returns:
this writer.
Throws:
IOException

endArray

public JsonWriter endArray()
                    throws IOException
Ends encoding the current array.

Returns:
this writer.
Throws:
IOException

beginObject

public JsonWriter beginObject()
                       throws IOException
Begins encoding a new object. Each call to this method must be paired with a call to endObject().

Returns:
this writer.
Throws:
IOException

endObject

public JsonWriter endObject()
                     throws IOException
Ends encoding the current object.

Returns:
this writer.
Throws:
IOException

name

public JsonWriter name(String name)
                throws IOException
Encodes the property name.

Parameters:
name - the name of the forthcoming value. May not be null.
Returns:
this writer.
Throws:
IOException

value

public JsonWriter value(String value)
                 throws IOException
Encodes value.

Parameters:
value - the literal string value, or null to encode a null literal.
Returns:
this writer.
Throws:
IOException

nullValue

public JsonWriter nullValue()
                     throws IOException
Encodes null.

Returns:
this writer.
Throws:
IOException

value

public JsonWriter value(boolean value)
                 throws IOException
Encodes value.

Returns:
this writer.
Throws:
IOException

value

public JsonWriter value(double value)
                 throws IOException
Encodes value.

Parameters:
value - a finite value. May not be NaNs or infinities.
Returns:
this writer.
Throws:
IOException

value

public JsonWriter value(long value)
                 throws IOException
Encodes value.

Returns:
this writer.
Throws:
IOException

value

public JsonWriter value(Number value)
                 throws IOException
Encodes value.

Parameters:
value - a finite value. May not be NaNs or infinities.
Returns:
this writer.
Throws:
IOException

flush

public void flush()
           throws IOException
Ensures all buffered data is written to the underlying Writer and flushes that writer.

Specified by:
flush in interface Flushable
Throws:
IOException

close

public void close()
           throws IOException
Flushes and closes this writer and the underlying Writer.

Specified by:
close in interface Closeable
Throws:
IOException - if the JSON document is incomplete.


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/stream/MalformedJsonException.html000066400000000000000000000413011316034351600322150ustar00rootroot00000000000000 MalformedJsonException (Gson 2.3.1 API)

com.google.gson.stream
Class MalformedJsonException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by java.io.IOException
              extended by com.google.gson.stream.MalformedJsonException
All Implemented Interfaces:
Serializable

public final class MalformedJsonException
extends IOException

Thrown when a reader encounters malformed JSON. Some syntax errors can be ignored by calling JsonReader.setLenient(boolean).

See Also:
Serialized Form

Constructor Summary
MalformedJsonException(String msg)
           
MalformedJsonException(String msg, Throwable throwable)
           
MalformedJsonException(Throwable throwable)
           
 
Method Summary
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

MalformedJsonException

public MalformedJsonException(String msg)

MalformedJsonException

public MalformedJsonException(String msg,
                              Throwable throwable)

MalformedJsonException

public MalformedJsonException(Throwable throwable)


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/stream/class-use/000077500000000000000000000000001316034351600266105ustar00rootroot00000000000000gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/stream/class-use/JsonReader.html000066400000000000000000000232341316034351600315360ustar00rootroot00000000000000 Uses of Class com.google.gson.stream.JsonReader (Gson 2.3.1 API)

Uses of Class
com.google.gson.stream.JsonReader

Packages that use JsonReader
com.google.gson This package provides the Gson class to convert Json to Java and vice-versa. 
 

Uses of JsonReader in com.google.gson
 

Methods in com.google.gson with parameters of type JsonReader
<T> T
Gson.fromJson(JsonReader reader, Type typeOfT)
          Reads the next JSON value from reader and convert it to an object of type typeOfT.
 JsonElement JsonParser.parse(JsonReader json)
          Returns the next value from the JSON stream as a parse tree.
abstract  T TypeAdapter.read(JsonReader in)
          Reads one JSON value (an array, object, string, number, boolean or null) and converts it to a Java object.
 



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/stream/class-use/JsonToken.html000066400000000000000000000216771316034351600314250ustar00rootroot00000000000000 Uses of Class com.google.gson.stream.JsonToken (Gson 2.3.1 API)

Uses of Class
com.google.gson.stream.JsonToken

Packages that use JsonToken
com.google.gson.stream   
 

Uses of JsonToken in com.google.gson.stream
 

Methods in com.google.gson.stream that return JsonToken
 JsonToken JsonReader.peek()
          Returns the type of the next token without consuming it.
static JsonToken JsonToken.valueOf(String name)
          Returns the enum constant of this type with the specified name.
static JsonToken[] JsonToken.values()
          Returns an array containing the constants of this enum type, in the order they are declared.
 



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/stream/class-use/JsonWriter.html000066400000000000000000000411251316034351600316070ustar00rootroot00000000000000 Uses of Class com.google.gson.stream.JsonWriter (Gson 2.3.1 API)

Uses of Class
com.google.gson.stream.JsonWriter

Packages that use JsonWriter
com.google.gson This package provides the Gson class to convert Json to Java and vice-versa. 
com.google.gson.stream   
 

Uses of JsonWriter in com.google.gson
 

Methods in com.google.gson with parameters of type JsonWriter
 void Gson.toJson(JsonElement jsonElement, JsonWriter writer)
          Writes the JSON for jsonElement to writer.
 void Gson.toJson(Object src, Type typeOfSrc, JsonWriter writer)
          Writes the JSON representation of src of type typeOfSrc to writer.
abstract  void TypeAdapter.write(JsonWriter out, T value)
          Writes one JSON value (an array, object, string, number, boolean or null) for value.
 

Uses of JsonWriter in com.google.gson.stream
 

Methods in com.google.gson.stream that return JsonWriter
 JsonWriter JsonWriter.beginArray()
          Begins encoding a new array.
 JsonWriter JsonWriter.beginObject()
          Begins encoding a new object.
 JsonWriter JsonWriter.endArray()
          Ends encoding the current array.
 JsonWriter JsonWriter.endObject()
          Ends encoding the current object.
 JsonWriter JsonWriter.name(String name)
          Encodes the property name.
 JsonWriter JsonWriter.nullValue()
          Encodes null.
 JsonWriter JsonWriter.value(boolean value)
          Encodes value.
 JsonWriter JsonWriter.value(double value)
          Encodes value.
 JsonWriter JsonWriter.value(long value)
          Encodes value.
 JsonWriter JsonWriter.value(Number value)
          Encodes value.
 JsonWriter JsonWriter.value(String value)
          Encodes value.
 



Copyright © 2008–2014 Google, Inc.. All rights reserved. MalformedJsonException.html000066400000000000000000000140441316034351600340410ustar00rootroot00000000000000gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/stream/class-use Uses of Class com.google.gson.stream.MalformedJsonException (Gson 2.3.1 API)

Uses of Class
com.google.gson.stream.MalformedJsonException

No usage of com.google.gson.stream.MalformedJsonException



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/stream/package-frame.html000066400000000000000000000031771316034351600302720ustar00rootroot00000000000000 com.google.gson.stream (Gson 2.3.1 API) com.google.gson.stream
Classes 
JsonReader
JsonWriter
Enums 
JsonToken
Exceptions 
MalformedJsonException
gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/stream/package-summary.html000066400000000000000000000170061316034351600306710ustar00rootroot00000000000000 com.google.gson.stream (Gson 2.3.1 API)

Package com.google.gson.stream

Class Summary
JsonReader Reads a JSON (RFC 4627) encoded value as a stream of tokens.
JsonWriter Writes a JSON (RFC 4627) encoded value to a stream, one token at a time.
 

Enum Summary
JsonToken A structure, name or value type in a JSON-encoded string.
 

Exception Summary
MalformedJsonException Thrown when a reader encounters malformed JSON.
 



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/stream/package-tree.html000066400000000000000000000211231316034351600301260ustar00rootroot00000000000000 com.google.gson.stream Class Hierarchy (Gson 2.3.1 API)

Hierarchy For Package com.google.gson.stream

Package Hierarchies:
All Packages

Class Hierarchy

Enum Hierarchy



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/com/google/gson/stream/package-use.html000066400000000000000000000210421316034351600277630ustar00rootroot00000000000000 Uses of Package com.google.gson.stream (Gson 2.3.1 API)

Uses of Package
com.google.gson.stream

Packages that use com.google.gson.stream
com.google.gson This package provides the Gson class to convert Json to Java and vice-versa. 
com.google.gson.stream   
 

Classes in com.google.gson.stream used by com.google.gson
JsonReader
          Reads a JSON (RFC 4627) encoded value as a stream of tokens.
JsonWriter
          Writes a JSON (RFC 4627) encoded value to a stream, one token at a time.
 

Classes in com.google.gson.stream used by com.google.gson.stream
JsonToken
          A structure, name or value type in a JSON-encoded string.
JsonWriter
          Writes a JSON (RFC 4627) encoded value to a stream, one token at a time.
 



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/constant-values.html000066400000000000000000000123401316034351600244320ustar00rootroot00000000000000 Constant Field Values (Gson 2.3.1 API)

Constant Field Values


Contents


Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/deprecated-list.html000066400000000000000000000161251316034351600243620ustar00rootroot00000000000000 Deprecated List (Gson 2.3.1 API)

Deprecated API


Contents
Deprecated Methods
com.google.gson.reflect.TypeToken.isAssignableFrom(Class)
          this implementation may be inconsistent with javac for types with wildcards. 
com.google.gson.reflect.TypeToken.isAssignableFrom(Type)
          this implementation may be inconsistent with javac for types with wildcards. 
com.google.gson.reflect.TypeToken.isAssignableFrom(TypeToken)
          this implementation may be inconsistent with javac for types with wildcards. 
 

Deprecated Constructors
com.google.gson.JsonNull()
           
 



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/help-doc.html000066400000000000000000000232661316034351600230100ustar00rootroot00000000000000 API Help (Gson 2.3.1 API)

How This API Document Is Organized

This API (Application Programming Interface) document has pages corresponding to the items in the navigation bar, described as follows.

Overview

The Overview page is the front page of this API document and provides a list of all packages with a summary for each. This page can also contain an overall description of the set of packages.

Package

Each package has a page that contains a list of its classes and interfaces, with a summary for each. This page can contain four categories:

  • Interfaces (italic)
  • Classes
  • Enums
  • Exceptions
  • Errors
  • Annotation Types

Class/Interface

Each class, interface, nested class and nested interface has its own separate page. Each of these pages has three sections consisting of a class/interface description, summary tables, and detailed member descriptions:

  • Class inheritance diagram
  • Direct Subclasses
  • All Known Subinterfaces
  • All Known Implementing Classes
  • Class/interface declaration
  • Class/interface description

  • Nested Class Summary
  • Field Summary
  • Constructor Summary
  • Method Summary

  • Field Detail
  • Constructor Detail
  • Method Detail
Each summary entry contains the first sentence from the detailed description for that item. The summary entries are alphabetical, while the detailed descriptions are in the order they appear in the source code. This preserves the logical groupings established by the programmer.

Annotation Type

Each annotation type has its own separate page with the following sections:

  • Annotation Type declaration
  • Annotation Type description
  • Required Element Summary
  • Optional Element Summary
  • Element Detail

Enum

Each enum has its own separate page with the following sections:

  • Enum declaration
  • Enum description
  • Enum Constant Summary
  • Enum Constant Detail

Use

Each documented package, class and interface has its own Use page. This page describes what packages, classes, methods, constructors and fields use any part of the given class or package. Given a class or interface A, its Use page includes subclasses of A, fields declared as A, methods that return A, and methods and constructors with parameters of type A. You can access this page by first going to the package, class or interface, then clicking on the "Use" link in the navigation bar.

Tree (Class Hierarchy)

There is a Class Hierarchy page for all packages, plus a hierarchy for each package. Each hierarchy page contains a list of classes and a list of interfaces. The classes are organized by inheritance structure starting with java.lang.Object. The interfaces do not inherit from java.lang.Object.
  • When viewing the Overview page, clicking on "Tree" displays the hierarchy for all packages.
  • When viewing a particular package, class or interface page, clicking "Tree" displays the hierarchy for only that package.

Deprecated API

The Deprecated API page lists all of the API that have been deprecated. A deprecated API is not recommended for use, generally due to improvements, and a replacement API is usually given. Deprecated APIs may be removed in future implementations.

Index

The Index contains an alphabetic list of all classes, interfaces, constructors, methods, and fields.

Prev/Next

These links take you to the next or previous class, interface, package, or related page.

Frames/No Frames

These links show and hide the HTML frames. All pages are available with or without frames.

Serialized Form

Each serializable or externalizable class has a description of its serialization fields and methods. This information is of interest to re-implementors, not to developers using the API. While there is no link in the navigation bar, you can get to this information by going to any serialized class and clicking "Serialized Form" in the "See also" section of the class description.

Constant Field Values

The Constant Field Values page lists the static final fields and their values.

This help file applies to API documentation generated using the standard doclet.



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/index-all.html000066400000000000000000002761051316034351600231740ustar00rootroot00000000000000 Index (Gson 2.3.1 API)
A B C D E F G H I J L M N P R S T U V W

A

add(JsonElement) - Method in class com.google.gson.JsonArray
Adds the specified element to self.
add(String, JsonElement) - Method in class com.google.gson.JsonObject
Adds a member, which is a name-value pair, to self.
addAll(JsonArray) - Method in class com.google.gson.JsonArray
Adds all the elements of the specified array to self.
addDeserializationExclusionStrategy(ExclusionStrategy) - Method in class com.google.gson.GsonBuilder
Configures Gson to apply the passed in exclusion strategy during deserialization.
addProperty(String, String) - Method in class com.google.gson.JsonObject
Convenience method to add a primitive member.
addProperty(String, Number) - Method in class com.google.gson.JsonObject
Convenience method to add a primitive member.
addProperty(String, Boolean) - Method in class com.google.gson.JsonObject
Convenience method to add a boolean member.
addProperty(String, Character) - Method in class com.google.gson.JsonObject
Convenience method to add a char member.
addSerializationExclusionStrategy(ExclusionStrategy) - Method in class com.google.gson.GsonBuilder
Configures Gson to apply the passed in exclusion strategy during serialization.

B

beginArray() - Method in class com.google.gson.stream.JsonReader
Consumes the next token from the JSON stream and asserts that it is the beginning of a new array.
beginArray() - Method in class com.google.gson.stream.JsonWriter
Begins encoding a new array.
beginObject() - Method in class com.google.gson.stream.JsonReader
Consumes the next token from the JSON stream and asserts that it is the beginning of a new object.
beginObject() - Method in class com.google.gson.stream.JsonWriter
Begins encoding a new object.

C

close() - Method in class com.google.gson.stream.JsonReader
Closes this JSON reader and the underlying Reader.
close() - Method in class com.google.gson.stream.JsonWriter
Flushes and closes this writer and the underlying Writer.
com.google.gson - package com.google.gson
This package provides the Gson class to convert Json to Java and vice-versa.
com.google.gson.annotations - package com.google.gson.annotations
This package provides annotations that can be used with Gson.
com.google.gson.reflect - package com.google.gson.reflect
This package provides utility classes for finding type information for generic types.
com.google.gson.stream - package com.google.gson.stream
 
contains(JsonElement) - Method in class com.google.gson.JsonArray
Returns true if this array contains the specified element.
create() - Method in class com.google.gson.GsonBuilder
Creates a Gson instance based on the current configuration.
create(Gson, TypeToken<T>) - Method in interface com.google.gson.TypeAdapterFactory
Returns a type adapter for type, or null if this factory doesn't support type.
createInstance(Type) - Method in interface com.google.gson.InstanceCreator
Gson invokes this call-back method during deserialization to create an instance of the specified type.

D

deserialize(JsonElement, Type) - Method in interface com.google.gson.JsonDeserializationContext
Invokes default deserialization on the specified object.
deserialize(JsonElement, Type, JsonDeserializationContext) - Method in interface com.google.gson.JsonDeserializer
Gson invokes this call-back method during deserialization when it encounters a field of the specified type.
disableHtmlEscaping() - Method in class com.google.gson.GsonBuilder
By default, Gson escapes HTML characters such as < > etc.
disableInnerClassSerialization() - Method in class com.google.gson.GsonBuilder
Configures Gson to exclude inner classes during serialization.

E

enableComplexMapKeySerialization() - Method in class com.google.gson.GsonBuilder
Enabling this feature will only change the serialized form if the map key is a complex type (i.e.
endArray() - Method in class com.google.gson.stream.JsonReader
Consumes the next token from the JSON stream and asserts that it is the end of the current array.
endArray() - Method in class com.google.gson.stream.JsonWriter
Ends encoding the current array.
endObject() - Method in class com.google.gson.stream.JsonReader
Consumes the next token from the JSON stream and asserts that it is the end of the current object.
endObject() - Method in class com.google.gson.stream.JsonWriter
Ends encoding the current object.
entrySet() - Method in class com.google.gson.JsonObject
Returns a set of members of this object.
equals(Object) - Method in class com.google.gson.JsonArray
 
equals(Object) - Method in class com.google.gson.JsonNull
All instances of JsonNull are the same
equals(Object) - Method in class com.google.gson.JsonObject
 
equals(Object) - Method in class com.google.gson.JsonPrimitive
 
equals(Object) - Method in class com.google.gson.reflect.TypeToken
 
excludeFieldsWithModifiers(int...) - Method in class com.google.gson.GsonBuilder
Configures Gson to excludes all class fields that have the specified modifiers.
excludeFieldsWithoutExposeAnnotation() - Method in class com.google.gson.GsonBuilder
Configures Gson to exclude all fields from consideration for serialization or deserialization that do not have the Expose annotation.
ExclusionStrategy - Interface in com.google.gson
A strategy (or policy) definition that is used to decide whether or not a field or top-level class should be serialized or deserialized as part of the JSON output/input.
Expose - Annotation Type in com.google.gson.annotations
An annotation that indicates this member should be exposed for JSON serialization or deserialization.

F

FieldAttributes - Class in com.google.gson
A data object that stores attributes of a field.
FieldAttributes(Field) - Constructor for class com.google.gson.FieldAttributes
Constructs a Field Attributes object from the f.
FieldNamingPolicy - Enum in com.google.gson
An enumeration that defines a few standard naming conventions for JSON field names.
FieldNamingStrategy - Interface in com.google.gson
A mechanism for providing custom field naming in Gson.
flush() - Method in class com.google.gson.stream.JsonWriter
Ensures all buffered data is written to the underlying Writer and flushes that writer.
fromJson(String, Class<T>) - Method in class com.google.gson.Gson
This method deserializes the specified Json into an object of the specified class.
fromJson(String, Type) - Method in class com.google.gson.Gson
This method deserializes the specified Json into an object of the specified type.
fromJson(Reader, Class<T>) - Method in class com.google.gson.Gson
This method deserializes the Json read from the specified reader into an object of the specified class.
fromJson(Reader, Type) - Method in class com.google.gson.Gson
This method deserializes the Json read from the specified reader into an object of the specified type.
fromJson(JsonReader, Type) - Method in class com.google.gson.Gson
Reads the next JSON value from reader and convert it to an object of type typeOfT.
fromJson(JsonElement, Class<T>) - Method in class com.google.gson.Gson
This method deserializes the Json read from the specified parse tree into an object of the specified type.
fromJson(JsonElement, Type) - Method in class com.google.gson.Gson
This method deserializes the Json read from the specified parse tree into an object of the specified type.
fromJson(Reader) - Method in class com.google.gson.TypeAdapter
Converts the JSON document in in to a Java object.
fromJson(String) - Method in class com.google.gson.TypeAdapter
Converts the JSON document in json to a Java object.
fromJsonTree(JsonElement) - Method in class com.google.gson.TypeAdapter
Converts jsonTree to a Java object.

G

generateNonExecutableJson() - Method in class com.google.gson.GsonBuilder
Makes the output JSON non-executable in Javascript by prefixing the generated JSON with some special text.
get(int) - Method in class com.google.gson.JsonArray
Returns the ith element of the array.
get(String) - Method in class com.google.gson.JsonObject
Returns the member with the specified name.
get(Type) - Static method in class com.google.gson.reflect.TypeToken
Gets type literal for the given Type instance.
get(Class<T>) - Static method in class com.google.gson.reflect.TypeToken
Gets type literal for the given Class instance.
getAdapter(TypeToken<T>) - Method in class com.google.gson.Gson
Returns the type adapter for type.
getAdapter(Class<T>) - Method in class com.google.gson.Gson
Returns the type adapter for type.
getAnnotation(Class<T>) - Method in class com.google.gson.FieldAttributes
Return the T annotation object from this field if it exist; otherwise returns null.
getAnnotations() - Method in class com.google.gson.FieldAttributes
Return the annotations that are present on this field.
getAsBigDecimal() - Method in class com.google.gson.JsonArray
convenience method to get this array as a BigDecimal if it contains a single element.
getAsBigDecimal() - Method in class com.google.gson.JsonElement
convenience method to get this element as a BigDecimal.
getAsBigDecimal() - Method in class com.google.gson.JsonPrimitive
convenience method to get this element as a BigDecimal.
getAsBigInteger() - Method in class com.google.gson.JsonArray
convenience method to get this array as a BigInteger if it contains a single element.
getAsBigInteger() - Method in class com.google.gson.JsonElement
convenience method to get this element as a BigInteger.
getAsBigInteger() - Method in class com.google.gson.JsonPrimitive
convenience method to get this element as a BigInteger.
getAsBoolean() - Method in class com.google.gson.JsonArray
convenience method to get this array as a boolean if it contains a single element.
getAsBoolean() - Method in class com.google.gson.JsonElement
convenience method to get this element as a boolean value.
getAsBoolean() - Method in class com.google.gson.JsonPrimitive
convenience method to get this element as a boolean value.
getAsByte() - Method in class com.google.gson.JsonArray
 
getAsByte() - Method in class com.google.gson.JsonElement
convenience method to get this element as a primitive byte value.
getAsByte() - Method in class com.google.gson.JsonPrimitive
 
getAsCharacter() - Method in class com.google.gson.JsonArray
 
getAsCharacter() - Method in class com.google.gson.JsonElement
convenience method to get this element as a primitive character value.
getAsCharacter() - Method in class com.google.gson.JsonPrimitive
 
getAsDouble() - Method in class com.google.gson.JsonArray
convenience method to get this array as a double if it contains a single element.
getAsDouble() - Method in class com.google.gson.JsonElement
convenience method to get this element as a primitive double value.
getAsDouble() - Method in class com.google.gson.JsonPrimitive
convenience method to get this element as a primitive double.
getAsFloat() - Method in class com.google.gson.JsonArray
convenience method to get this array as a float if it contains a single element.
getAsFloat() - Method in class com.google.gson.JsonElement
convenience method to get this element as a primitive float value.
getAsFloat() - Method in class com.google.gson.JsonPrimitive
convenience method to get this element as a float.
getAsInt() - Method in class com.google.gson.JsonArray
convenience method to get this array as an integer if it contains a single element.
getAsInt() - Method in class com.google.gson.JsonElement
convenience method to get this element as a primitive integer value.
getAsInt() - Method in class com.google.gson.JsonPrimitive
convenience method to get this element as a primitive integer.
getAsJsonArray() - Method in class com.google.gson.JsonElement
convenience method to get this element as a JsonArray.
getAsJsonArray(String) - Method in class com.google.gson.JsonObject
Convenience method to get the specified member as a JsonArray.
getAsJsonNull() - Method in class com.google.gson.JsonElement
convenience method to get this element as a JsonNull.
getAsJsonObject() - Method in class com.google.gson.JsonElement
convenience method to get this element as a JsonObject.
getAsJsonObject(String) - Method in class com.google.gson.JsonObject
Convenience method to get the specified member as a JsonObject.
getAsJsonPrimitive() - Method in class com.google.gson.JsonElement
convenience method to get this element as a JsonPrimitive.
getAsJsonPrimitive(String) - Method in class com.google.gson.JsonObject
Convenience method to get the specified member as a JsonPrimitive element.
getAsLong() - Method in class com.google.gson.JsonArray
convenience method to get this array as a long if it contains a single element.
getAsLong() - Method in class com.google.gson.JsonElement
convenience method to get this element as a primitive long value.
getAsLong() - Method in class com.google.gson.JsonPrimitive
convenience method to get this element as a primitive long.
getAsNumber() - Method in class com.google.gson.JsonArray
convenience method to get this array as a Number if it contains a single element.
getAsNumber() - Method in class com.google.gson.JsonElement
convenience method to get this element as a Number.
getAsNumber() - Method in class com.google.gson.JsonPrimitive
convenience method to get this element as a Number.
getAsShort() - Method in class com.google.gson.JsonArray
convenience method to get this array as a primitive short if it contains a single element.
getAsShort() - Method in class com.google.gson.JsonElement
convenience method to get this element as a primitive short value.
getAsShort() - Method in class com.google.gson.JsonPrimitive
convenience method to get this element as a primitive short.
getAsString() - Method in class com.google.gson.JsonArray
convenience method to get this array as a String if it contains a single element.
getAsString() - Method in class com.google.gson.JsonElement
convenience method to get this element as a string value.
getAsString() - Method in class com.google.gson.JsonPrimitive
convenience method to get this element as a String.
getDeclaredClass() - Method in class com.google.gson.FieldAttributes
Returns the Class object that was declared for this field.
getDeclaredType() - Method in class com.google.gson.FieldAttributes
For example, assume the following class definition:
 public class Foo {
   private String bar;
   private List<String> red;
 }

 Type listParmeterizedType = new TypeToken<List<String>>() {}.getType();
getDeclaringClass() - Method in class com.google.gson.FieldAttributes
 
getDelegateAdapter(TypeAdapterFactory, TypeToken<T>) - Method in class com.google.gson.Gson
This method is used to get an alternate type adapter for the specified type.
getName() - Method in class com.google.gson.FieldAttributes
 
getPath() - Method in class com.google.gson.stream.JsonReader
Returns a JsonPath to the current location in the JSON value.
getRawType() - Method in class com.google.gson.reflect.TypeToken
Returns the raw (non-generic) type for this type.
getSerializeNulls() - Method in class com.google.gson.stream.JsonWriter
Returns true if object members are serialized when their value is null.
getType() - Method in class com.google.gson.reflect.TypeToken
Gets underlying Type instance.
Gson - Class in com.google.gson
This is the main class for using Gson.
Gson() - Constructor for class com.google.gson.Gson
Constructs a Gson object with default configuration.
GsonBuilder - Class in com.google.gson
Use this builder to construct a Gson instance when you need to set configuration options other than the default.
GsonBuilder() - Constructor for class com.google.gson.GsonBuilder
Creates a GsonBuilder instance that can be used to build Gson with various configuration settings.

H

has(String) - Method in class com.google.gson.JsonObject
Convenience method to check if a member with the specified name is present in this object.
hashCode() - Method in class com.google.gson.JsonArray
 
hashCode() - Method in class com.google.gson.JsonNull
All instances of JsonNull have the same hash code since they are indistinguishable
hashCode() - Method in class com.google.gson.JsonObject
 
hashCode() - Method in class com.google.gson.JsonPrimitive
 
hashCode() - Method in class com.google.gson.reflect.TypeToken
 
hasModifier(int) - Method in class com.google.gson.FieldAttributes
Returns true if the field is defined with the modifier.
hasNext() - Method in class com.google.gson.JsonStreamParser
Returns true if a JsonElement is available on the input for consumption
hasNext() - Method in class com.google.gson.stream.JsonReader
Returns true if the current array or object has another element.

I

INSTANCE - Static variable in class com.google.gson.JsonNull
singleton for JsonNull
InstanceCreator<T> - Interface in com.google.gson
This interface is implemented to create instances of a class that does not define a no-args constructor.
isAssignableFrom(Class<?>) - Method in class com.google.gson.reflect.TypeToken
Deprecated. this implementation may be inconsistent with javac for types with wildcards.
isAssignableFrom(Type) - Method in class com.google.gson.reflect.TypeToken
Deprecated. this implementation may be inconsistent with javac for types with wildcards.
isAssignableFrom(TypeToken<?>) - Method in class com.google.gson.reflect.TypeToken
Deprecated. this implementation may be inconsistent with javac for types with wildcards.
isBoolean() - Method in class com.google.gson.JsonPrimitive
Check whether this primitive contains a boolean value.
isHtmlSafe() - Method in class com.google.gson.stream.JsonWriter
Returns true if this writer writes JSON that's safe for inclusion in HTML and XML documents.
isJsonArray() - Method in class com.google.gson.JsonElement
provides check for verifying if this element is an array or not.
isJsonNull() - Method in class com.google.gson.JsonElement
provides check for verifying if this element represents a null value or not.
isJsonObject() - Method in class com.google.gson.JsonElement
provides check for verifying if this element is a Json object or not.
isJsonPrimitive() - Method in class com.google.gson.JsonElement
provides check for verifying if this element is a primitive or not.
isLenient() - Method in class com.google.gson.stream.JsonReader
Returns true if this parser is liberal in what it accepts.
isLenient() - Method in class com.google.gson.stream.JsonWriter
Returns true if this writer has relaxed syntax rules.
isNumber() - Method in class com.google.gson.JsonPrimitive
Check whether this primitive contains a Number.
isString() - Method in class com.google.gson.JsonPrimitive
Check whether this primitive contains a String value.
iterator() - Method in class com.google.gson.JsonArray
Returns an iterator to navigate the elemetns of the array.

J

JsonAdapter - Annotation Type in com.google.gson.annotations
An annotation that indicates the Gson TypeAdapter to use with a class or field.
JsonArray - Class in com.google.gson
A class representing an array type in Json.
JsonArray() - Constructor for class com.google.gson.JsonArray
Creates an empty JsonArray.
JsonDeserializationContext - Interface in com.google.gson
Context for deserialization that is passed to a custom deserializer during invocation of its JsonDeserializer.deserialize(JsonElement, Type, JsonDeserializationContext) method.
JsonDeserializer<T> - Interface in com.google.gson
Interface representing a custom deserializer for Json.
JsonElement - Class in com.google.gson
A class representing an element of Json.
JsonElement() - Constructor for class com.google.gson.JsonElement
 
JsonIOException - Exception in com.google.gson
This exception is raised when Gson was unable to read an input stream or write to one.
JsonIOException(String) - Constructor for exception com.google.gson.JsonIOException
 
JsonIOException(String, Throwable) - Constructor for exception com.google.gson.JsonIOException
 
JsonIOException(Throwable) - Constructor for exception com.google.gson.JsonIOException
Creates exception with the specified cause.
JsonNull - Class in com.google.gson
A class representing a Json null value.
JsonNull() - Constructor for class com.google.gson.JsonNull
Deprecated. 
JsonObject - Class in com.google.gson
A class representing an object type in Json.
JsonObject() - Constructor for class com.google.gson.JsonObject
 
JsonParseException - Exception in com.google.gson
This exception is raised if there is a serious issue that occurs during parsing of a Json string.
JsonParseException(String) - Constructor for exception com.google.gson.JsonParseException
Creates exception with the specified message.
JsonParseException(String, Throwable) - Constructor for exception com.google.gson.JsonParseException
Creates exception with the specified message and cause.
JsonParseException(Throwable) - Constructor for exception com.google.gson.JsonParseException
Creates exception with the specified cause.
JsonParser - Class in com.google.gson
A parser to parse Json into a parse tree of JsonElements
JsonParser() - Constructor for class com.google.gson.JsonParser
 
JsonPrimitive - Class in com.google.gson
A class representing a Json primitive value.
JsonPrimitive(Boolean) - Constructor for class com.google.gson.JsonPrimitive
Create a primitive containing a boolean value.
JsonPrimitive(Number) - Constructor for class com.google.gson.JsonPrimitive
Create a primitive containing a Number.
JsonPrimitive(String) - Constructor for class com.google.gson.JsonPrimitive
Create a primitive containing a String value.
JsonPrimitive(Character) - Constructor for class com.google.gson.JsonPrimitive
Create a primitive containing a character.
JsonReader - Class in com.google.gson.stream
Reads a JSON (RFC 4627) encoded value as a stream of tokens.
JsonReader(Reader) - Constructor for class com.google.gson.stream.JsonReader
Creates a new instance that reads a JSON-encoded stream from in.
JsonSerializationContext - Interface in com.google.gson
Context for serialization that is passed to a custom serializer during invocation of its JsonSerializer.serialize(Object, Type, JsonSerializationContext) method.
JsonSerializer<T> - Interface in com.google.gson
Interface representing a custom serializer for Json.
JsonStreamParser - Class in com.google.gson
A streaming parser that allows reading of multiple JsonElements from the specified reader asynchronously.
JsonStreamParser(String) - Constructor for class com.google.gson.JsonStreamParser
 
JsonStreamParser(Reader) - Constructor for class com.google.gson.JsonStreamParser
 
JsonSyntaxException - Exception in com.google.gson
This exception is raised when Gson attempts to read (or write) a malformed JSON element.
JsonSyntaxException(String) - Constructor for exception com.google.gson.JsonSyntaxException
 
JsonSyntaxException(String, Throwable) - Constructor for exception com.google.gson.JsonSyntaxException
 
JsonSyntaxException(Throwable) - Constructor for exception com.google.gson.JsonSyntaxException
Creates exception with the specified cause.
JsonToken - Enum in com.google.gson.stream
A structure, name or value type in a JSON-encoded string.
JsonWriter - Class in com.google.gson.stream
Writes a JSON (RFC 4627) encoded value to a stream, one token at a time.
JsonWriter(Writer) - Constructor for class com.google.gson.stream.JsonWriter
Creates a new instance that writes a JSON-encoded stream to out.

L

LongSerializationPolicy - Enum in com.google.gson
Defines the expected format for a long or Long type when its serialized.

M

MalformedJsonException - Exception in com.google.gson.stream
Thrown when a reader encounters malformed JSON.
MalformedJsonException(String) - Constructor for exception com.google.gson.stream.MalformedJsonException
 
MalformedJsonException(String, Throwable) - Constructor for exception com.google.gson.stream.MalformedJsonException
 
MalformedJsonException(Throwable) - Constructor for exception com.google.gson.stream.MalformedJsonException
 

N

name(String) - Method in class com.google.gson.stream.JsonWriter
Encodes the property name.
next() - Method in class com.google.gson.JsonStreamParser
Returns the next available JsonElement on the reader.
nextBoolean() - Method in class com.google.gson.stream.JsonReader
Returns the boolean value of the next token, consuming it.
nextDouble() - Method in class com.google.gson.stream.JsonReader
Returns the double value of the next token, consuming it.
nextInt() - Method in class com.google.gson.stream.JsonReader
Returns the int value of the next token, consuming it.
nextLong() - Method in class com.google.gson.stream.JsonReader
Returns the long value of the next token, consuming it.
nextName() - Method in class com.google.gson.stream.JsonReader
Returns the next token, a property name, and consumes it.
nextNull() - Method in class com.google.gson.stream.JsonReader
Consumes the next token from the JSON stream and asserts that it is a literal null.
nextString() - Method in class com.google.gson.stream.JsonReader
Returns the string value of the next token, consuming it.
nullSafe() - Method in class com.google.gson.TypeAdapter
This wrapper method is used to make a type adapter null tolerant.
nullValue() - Method in class com.google.gson.stream.JsonWriter
Encodes null.

P

parse(String) - Method in class com.google.gson.JsonParser
Parses the specified JSON string into a parse tree
parse(Reader) - Method in class com.google.gson.JsonParser
Parses the specified JSON string into a parse tree
parse(JsonReader) - Method in class com.google.gson.JsonParser
Returns the next value from the JSON stream as a parse tree.
peek() - Method in class com.google.gson.stream.JsonReader
Returns the type of the next token without consuming it.

R

read(JsonReader) - Method in class com.google.gson.TypeAdapter
Reads one JSON value (an array, object, string, number, boolean or null) and converts it to a Java object.
registerTypeAdapter(Type, Object) - Method in class com.google.gson.GsonBuilder
Configures Gson for custom serialization or deserialization.
registerTypeAdapterFactory(TypeAdapterFactory) - Method in class com.google.gson.GsonBuilder
Register a factory for type adapters.
registerTypeHierarchyAdapter(Class<?>, Object) - Method in class com.google.gson.GsonBuilder
Configures Gson for custom serialization or deserialization for an inheritance type hierarchy.
remove(JsonElement) - Method in class com.google.gson.JsonArray
Removes the first occurrence of the specified element from this array, if it is present.
remove(int) - Method in class com.google.gson.JsonArray
Removes the element at the specified position in this array.
remove(String) - Method in class com.google.gson.JsonObject
Removes the property from this JsonObject.
remove() - Method in class com.google.gson.JsonStreamParser
This optional Iterator method is not relevant for stream parsing and hence is not implemented.

S

serialize(Object) - Method in interface com.google.gson.JsonSerializationContext
Invokes default serialization on the specified object.
serialize(Object, Type) - Method in interface com.google.gson.JsonSerializationContext
Invokes default serialization on the specified object passing the specific type information.
serialize(T, Type, JsonSerializationContext) - Method in interface com.google.gson.JsonSerializer
Gson invokes this call-back method during serialization when it encounters a field of the specified type.
serialize(Long) - Method in enum com.google.gson.LongSerializationPolicy
Serialize this value using this serialization policy.
SerializedName - Annotation Type in com.google.gson.annotations
An annotation that indicates this member should be serialized to JSON with the provided name value as its field name.
serializeNulls() - Method in class com.google.gson.GsonBuilder
Configure Gson to serialize null fields.
serializeSpecialFloatingPointValues() - Method in class com.google.gson.GsonBuilder
Section 2.4 of JSON specification disallows special double values (NaN, Infinity, -Infinity).
set(int, JsonElement) - Method in class com.google.gson.JsonArray
Replaces the element at the specified position in this array with the specified element.
setDateFormat(String) - Method in class com.google.gson.GsonBuilder
Configures Gson to serialize Date objects according to the pattern provided.
setDateFormat(int) - Method in class com.google.gson.GsonBuilder
Configures Gson to to serialize Date objects according to the style value provided.
setDateFormat(int, int) - Method in class com.google.gson.GsonBuilder
Configures Gson to to serialize Date objects according to the style value provided.
setExclusionStrategies(ExclusionStrategy...) - Method in class com.google.gson.GsonBuilder
Configures Gson to apply a set of exclusion strategies during both serialization and deserialization.
setFieldNamingPolicy(FieldNamingPolicy) - Method in class com.google.gson.GsonBuilder
Configures Gson to apply a specific naming policy to an object's field during serialization and deserialization.
setFieldNamingStrategy(FieldNamingStrategy) - Method in class com.google.gson.GsonBuilder
Configures Gson to apply a specific naming policy strategy to an object's field during serialization and deserialization.
setHtmlSafe(boolean) - Method in class com.google.gson.stream.JsonWriter
Configure this writer to emit JSON that's safe for direct inclusion in HTML and XML documents.
setIndent(String) - Method in class com.google.gson.stream.JsonWriter
Sets the indentation string to be repeated for each level of indentation in the encoded document.
setLenient(boolean) - Method in class com.google.gson.stream.JsonReader
Configure this parser to be be liberal in what it accepts.
setLenient(boolean) - Method in class com.google.gson.stream.JsonWriter
Configure this writer to relax its syntax rules.
setLongSerializationPolicy(LongSerializationPolicy) - Method in class com.google.gson.GsonBuilder
Configures Gson to apply a specific serialization policy for Long and long objects.
setPrettyPrinting() - Method in class com.google.gson.GsonBuilder
Configures Gson to output Json that fits in a page for pretty printing.
setSerializeNulls(boolean) - Method in class com.google.gson.stream.JsonWriter
Sets whether object members are serialized when their value is null.
setVersion(double) - Method in class com.google.gson.GsonBuilder
Configures Gson to enable versioning support.
shouldSkipClass(Class<?>) - Method in interface com.google.gson.ExclusionStrategy
 
shouldSkipField(FieldAttributes) - Method in interface com.google.gson.ExclusionStrategy
 
Since - Annotation Type in com.google.gson.annotations
An annotation that indicates the version number since a member or a type has been present.
size() - Method in class com.google.gson.JsonArray
Returns the number of elements in the array.
skipValue() - Method in class com.google.gson.stream.JsonReader
Skips the next value recursively.

T

toJson(Object) - Method in class com.google.gson.Gson
This method serializes the specified object into its equivalent Json representation.
toJson(Object, Type) - Method in class com.google.gson.Gson
This method serializes the specified object, including those of generic types, into its equivalent Json representation.
toJson(Object, Appendable) - Method in class com.google.gson.Gson
This method serializes the specified object into its equivalent Json representation.
toJson(Object, Type, Appendable) - Method in class com.google.gson.Gson
This method serializes the specified object, including those of generic types, into its equivalent Json representation.
toJson(Object, Type, JsonWriter) - Method in class com.google.gson.Gson
Writes the JSON representation of src of type typeOfSrc to writer.
toJson(JsonElement) - Method in class com.google.gson.Gson
Converts a tree of JsonElements into its equivalent JSON representation.
toJson(JsonElement, Appendable) - Method in class com.google.gson.Gson
Writes out the equivalent JSON for a tree of JsonElements.
toJson(JsonElement, JsonWriter) - Method in class com.google.gson.Gson
Writes the JSON for jsonElement to writer.
toJson(Writer, T) - Method in class com.google.gson.TypeAdapter
Converts value to a JSON document and writes it to out.
toJson(T) - Method in class com.google.gson.TypeAdapter
Converts value to a JSON document.
toJsonTree(Object) - Method in class com.google.gson.Gson
This method serializes the specified object into its equivalent representation as a tree of JsonElements.
toJsonTree(Object, Type) - Method in class com.google.gson.Gson
This method serializes the specified object, including those of generic types, into its equivalent representation as a tree of JsonElements.
toJsonTree(T) - Method in class com.google.gson.TypeAdapter
Converts value to a JSON tree.
toString() - Method in class com.google.gson.Gson
 
toString() - Method in class com.google.gson.JsonElement
Returns a String representation of this element.
toString() - Method in class com.google.gson.reflect.TypeToken
 
toString() - Method in class com.google.gson.stream.JsonReader
 
translateName(Field) - Method in interface com.google.gson.FieldNamingStrategy
Translates the field name into its JSON field name representation.
TypeAdapter<T> - Class in com.google.gson
Converts Java objects to and from JSON.
TypeAdapter() - Constructor for class com.google.gson.TypeAdapter
 
TypeAdapterFactory - Interface in com.google.gson
Creates type adapters for set of related types.
TypeToken<T> - Class in com.google.gson.reflect
Represents a generic type T.
TypeToken() - Constructor for class com.google.gson.reflect.TypeToken
Constructs a new type literal.

U

Until - Annotation Type in com.google.gson.annotations
An annotation that indicates the version number until a member or a type should be present.

V

value(String) - Method in class com.google.gson.stream.JsonWriter
Encodes value.
value(boolean) - Method in class com.google.gson.stream.JsonWriter
Encodes value.
value(double) - Method in class com.google.gson.stream.JsonWriter
Encodes value.
value(long) - Method in class com.google.gson.stream.JsonWriter
Encodes value.
value(Number) - Method in class com.google.gson.stream.JsonWriter
Encodes value.
valueOf(String) - Static method in enum com.google.gson.FieldNamingPolicy
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum com.google.gson.LongSerializationPolicy
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum com.google.gson.stream.JsonToken
Returns the enum constant of this type with the specified name.
values() - Static method in enum com.google.gson.FieldNamingPolicy
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum com.google.gson.LongSerializationPolicy
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum com.google.gson.stream.JsonToken
Returns an array containing the constants of this enum type, in the order they are declared.

W

write(JsonWriter, T) - Method in class com.google.gson.TypeAdapter
Writes one JSON value (an array, object, string, number, boolean or null) for value.

A B C D E F G H I J L M N P R S T U V W

Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/index.html000066400000000000000000000051161316034351600224160ustar00rootroot00000000000000 Gson 2.3.1 API <H2> Frame Alert</H2> <P> 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. <BR> Link to<A HREF="overview-summary.html">Non-frame version.</A> gson-gson-parent-2.8.2/gson/docs/javadocs/overview-frame.html000066400000000000000000000026771316034351600242560ustar00rootroot00000000000000 Overview List (Gson 2.3.1 API)
All Classes

Packages
com.google.gson
com.google.gson.annotations
com.google.gson.reflect
com.google.gson.stream

  gson-gson-parent-2.8.2/gson/docs/javadocs/overview-summary.html000066400000000000000000000145551316034351600246570ustar00rootroot00000000000000 Overview (Gson 2.3.1 API)



Gson 2.3.1 API

Packages
com.google.gson This package provides the Gson class to convert Json to Java and vice-versa.
com.google.gson.annotations This package provides annotations that can be used with Gson.
com.google.gson.reflect This package provides utility classes for finding type information for generic types.
com.google.gson.stream  

 



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/overview-tree.html000066400000000000000000000346651316034351600241250ustar00rootroot00000000000000 Class Hierarchy (Gson 2.3.1 API)

Hierarchy For All Packages

Package Hierarchies:
com.google.gson, com.google.gson.annotations, com.google.gson.reflect, com.google.gson.stream

Class Hierarchy

Interface Hierarchy

Annotation Type Hierarchy

Enum Hierarchy



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/package-list000066400000000000000000000001331316034351600227020ustar00rootroot00000000000000com.google.gson com.google.gson.annotations com.google.gson.reflect com.google.gson.stream gson-gson-parent-2.8.2/gson/docs/javadocs/resources/000077500000000000000000000000001316034351600224305ustar00rootroot00000000000000gson-gson-parent-2.8.2/gson/docs/javadocs/resources/inherit.gif000066400000000000000000000000711316034351600245570ustar00rootroot00000000000000GIF89a, DrjԐ;߀Q@N;gson-gson-parent-2.8.2/gson/docs/javadocs/script.js000066400000000000000000000014731316034351600222650ustar00rootroot00000000000000function show(type) { count = 0; for (var key in methods) { var row = document.getElementById(key); if ((methods[key] & type) != 0) { row.style.display = ''; row.className = (count++ % 2) ? rowColor : altColor; } else row.style.display = 'none'; } updateTabs(type); } function updateTabs(type) { for (var value in tabs) { var sNode = document.getElementById(tabs[value][0]); var spanNode = sNode.firstChild; if (value == type) { sNode.className = activeTableTab; spanNode.innerHTML = tabs[value][1]; } else { sNode.className = tableTab; spanNode.innerHTML = "" + tabs[value][1] + ""; } } } gson-gson-parent-2.8.2/gson/docs/javadocs/serialized-form.html000066400000000000000000000201101316034351600243720ustar00rootroot00000000000000 Serialized Form (Gson 2.3.1 API)

Serialized Form


Package com.google.gson

Class com.google.gson.JsonIOException extends JsonParseException implements Serializable

serialVersionUID: 1L

Class com.google.gson.JsonParseException extends RuntimeException implements Serializable

serialVersionUID: -4086729973971783390L

Class com.google.gson.JsonSyntaxException extends JsonParseException implements Serializable

serialVersionUID: 1L


Package com.google.gson.stream

Class com.google.gson.stream.MalformedJsonException extends IOException implements Serializable

serialVersionUID: 1L



Copyright © 2008–2014 Google, Inc.. All rights reserved. gson-gson-parent-2.8.2/gson/docs/javadocs/stylesheet.css000066400000000000000000000025571316034351600233320ustar00rootroot00000000000000/* Javadoc style sheet */ /* Define colors, fonts and other style attributes here to override the defaults */ /* Page background color */ body { background-color: #FFFFFF; color:#000000 } /* Headings */ h1 { font-size: 145% } /* Table colors */ .TableHeadingColor { background: #CCCCFF; color:#000000 } /* Dark mauve */ .TableSubHeadingColor { background: #EEEEFF; color:#000000 } /* Light mauve */ .TableRowColor { background: #FFFFFF; color:#000000 } /* White */ /* Font used in left-hand frame lists */ .FrameTitleFont { font-size: 100%; font-family: Helvetica, Arial, sans-serif; color:#000000 } .FrameHeadingFont { font-size: 90%; font-family: Helvetica, Arial, sans-serif; color:#000000 } .FrameItemFont { font-size: 90%; font-family: Helvetica, Arial, sans-serif; color:#000000 } /* Navigation bar fonts and colors */ .NavBarCell1 { background-color:#EEEEFF; color:#000000} /* Light mauve */ .NavBarCell1Rev { background-color:#00008B; color:#FFFFFF} /* Dark Blue */ .NavBarFont1 { font-family: Arial, Helvetica, sans-serif; color:#000000;color:#000000;} .NavBarFont1Rev { font-family: Arial, Helvetica, sans-serif; color:#FFFFFF;color:#FFFFFF;} .NavBarCell2 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF; color:#000000} .NavBarCell3 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF; color:#000000} gson-gson-parent-2.8.2/gson/pom.xml000066400000000000000000000035451316034351600172200ustar00rootroot00000000000000 4.0.0 com.google.code.gson gson-parent 2.8.2 gson Gson junit junit test org.apache.maven.plugins maven-javadoc-plugin com.google.gson com.google.gson.internal:com.google.gson.internal.bind http://docs.oracle.com/javase/6/docs/api/ biz.aQute.bnd bnd-maven-plugin 3.1.0 bnd-process org.apache.maven.plugins maven-jar-plugin ${project.build.outputDirectory}/META-INF/MANIFEST.MF org.apache.felix maven-bundle-plugin gson-gson-parent-2.8.2/gson/src/000077500000000000000000000000001316034351600164635ustar00rootroot00000000000000gson-gson-parent-2.8.2/gson/src/main/000077500000000000000000000000001316034351600174075ustar00rootroot00000000000000gson-gson-parent-2.8.2/gson/src/main/java/000077500000000000000000000000001316034351600203305ustar00rootroot00000000000000gson-gson-parent-2.8.2/gson/src/main/java/com/000077500000000000000000000000001316034351600211065ustar00rootroot00000000000000gson-gson-parent-2.8.2/gson/src/main/java/com/google/000077500000000000000000000000001316034351600223625ustar00rootroot00000000000000gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/000077500000000000000000000000001316034351600233305ustar00rootroot00000000000000gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/DefaultDateTypeAdapter.java000066400000000000000000000111151316034351600305170ustar00rootroot00000000000000/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson; import java.io.IOException; import java.sql.Timestamp; import java.text.DateFormat; import java.text.ParseException; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import com.google.gson.internal.bind.util.ISO8601Utils; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; /** * This type adapter supports three subclasses of date: Date, Timestamp, and * java.sql.Date. * * @author Inderjeet Singh * @author Joel Leitch */ final class DefaultDateTypeAdapter extends TypeAdapter { private static final String SIMPLE_NAME = "DefaultDateTypeAdapter"; private final Class dateType; private final DateFormat enUsFormat; private final DateFormat localFormat; DefaultDateTypeAdapter(Class dateType) { this(dateType, DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.US), DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)); } DefaultDateTypeAdapter(Class dateType, String datePattern) { this(dateType, new SimpleDateFormat(datePattern, Locale.US), new SimpleDateFormat(datePattern)); } DefaultDateTypeAdapter(Class dateType, int style) { this(dateType, DateFormat.getDateInstance(style, Locale.US), DateFormat.getDateInstance(style)); } public DefaultDateTypeAdapter(int dateStyle, int timeStyle) { this(Date.class, DateFormat.getDateTimeInstance(dateStyle, timeStyle, Locale.US), DateFormat.getDateTimeInstance(dateStyle, timeStyle)); } public DefaultDateTypeAdapter(Class dateType, int dateStyle, int timeStyle) { this(dateType, DateFormat.getDateTimeInstance(dateStyle, timeStyle, Locale.US), DateFormat.getDateTimeInstance(dateStyle, timeStyle)); } DefaultDateTypeAdapter(final Class dateType, DateFormat enUsFormat, DateFormat localFormat) { if ( dateType != Date.class && dateType != java.sql.Date.class && dateType != Timestamp.class ) { throw new IllegalArgumentException("Date type must be one of " + Date.class + ", " + Timestamp.class + ", or " + java.sql.Date.class + " but was " + dateType); } this.dateType = dateType; this.enUsFormat = enUsFormat; this.localFormat = localFormat; } // These methods need to be synchronized since JDK DateFormat classes are not thread-safe // See issue 162 @Override public void write(JsonWriter out, Date value) throws IOException { if (value == null) { out.nullValue(); return; } synchronized (localFormat) { String dateFormatAsString = enUsFormat.format(value); out.value(dateFormatAsString); } } @Override public Date read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } Date date = deserializeToDate(in.nextString()); if (dateType == Date.class) { return date; } else if (dateType == Timestamp.class) { return new Timestamp(date.getTime()); } else if (dateType == java.sql.Date.class) { return new java.sql.Date(date.getTime()); } else { // This must never happen: dateType is guarded in the primary constructor throw new AssertionError(); } } private Date deserializeToDate(String s) { synchronized (localFormat) { try { return localFormat.parse(s); } catch (ParseException ignored) {} try { return enUsFormat.parse(s); } catch (ParseException ignored) {} try { return ISO8601Utils.parse(s, new ParsePosition(0)); } catch (ParseException e) { throw new JsonSyntaxException(s, e); } } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(SIMPLE_NAME); sb.append('(').append(localFormat.getClass().getSimpleName()).append(')'); return sb.toString(); } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/ExclusionStrategy.java000066400000000000000000000101411316034351600276640ustar00rootroot00000000000000/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson; /** * A strategy (or policy) definition that is used to decide whether or not a field or top-level * class should be serialized or deserialized as part of the JSON output/input. For serialization, * if the {@link #shouldSkipClass(Class)} method returns true then that class or field type * will not be part of the JSON output. For deserialization, if {@link #shouldSkipClass(Class)} * returns true, then it will not be set as part of the Java object structure. * *

The following are a few examples that shows how you can use this exclusion mechanism. * *

Exclude fields and objects based on a particular class type: *

 * private static class SpecificClassExclusionStrategy implements ExclusionStrategy {
 *   private final Class<?> excludedThisClass;
 *
 *   public SpecificClassExclusionStrategy(Class<?> excludedThisClass) {
 *     this.excludedThisClass = excludedThisClass;
 *   }
 *
 *   public boolean shouldSkipClass(Class<?> clazz) {
 *     return excludedThisClass.equals(clazz);
 *   }
 *
 *   public boolean shouldSkipField(FieldAttributes f) {
 *     return excludedThisClass.equals(f.getDeclaredClass());
 *   }
 * }
 * 
* *

Excludes fields and objects based on a particular annotation: *

 * public @interface FooAnnotation {
 *   // some implementation here
 * }
 *
 * // Excludes any field (or class) that is tagged with an "@FooAnnotation"
 * private static class FooAnnotationExclusionStrategy implements ExclusionStrategy {
 *   public boolean shouldSkipClass(Class<?> clazz) {
 *     return clazz.getAnnotation(FooAnnotation.class) != null;
 *   }
 *
 *   public boolean shouldSkipField(FieldAttributes f) {
 *     return f.getAnnotation(FooAnnotation.class) != null;
 *   }
 * }
 * 
* *

Now if you want to configure {@code Gson} to use a user defined exclusion strategy, then * the {@code GsonBuilder} is required. The following is an example of how you can use the * {@code GsonBuilder} to configure Gson to use one of the above sample: *

 * ExclusionStrategy excludeStrings = new UserDefinedExclusionStrategy(String.class);
 * Gson gson = new GsonBuilder()
 *     .setExclusionStrategies(excludeStrings)
 *     .create();
 * 
* *

For certain model classes, you may only want to serialize a field, but exclude it for * deserialization. To do that, you can write an {@code ExclusionStrategy} as per normal; * however, you would register it with the * {@link GsonBuilder#addDeserializationExclusionStrategy(ExclusionStrategy)} method. * For example: *

 * ExclusionStrategy excludeStrings = new UserDefinedExclusionStrategy(String.class);
 * Gson gson = new GsonBuilder()
 *     .addDeserializationExclusionStrategy(excludeStrings)
 *     .create();
 * 
* * @author Inderjeet Singh * @author Joel Leitch * * @see GsonBuilder#setExclusionStrategies(ExclusionStrategy...) * @see GsonBuilder#addDeserializationExclusionStrategy(ExclusionStrategy) * @see GsonBuilder#addSerializationExclusionStrategy(ExclusionStrategy) * * @since 1.4 */ public interface ExclusionStrategy { /** * @param f the field object that is under test * @return true if the field should be ignored; otherwise false */ public boolean shouldSkipField(FieldAttributes f); /** * @param clazz the class object that is under test * @return true if the class should be ignored; otherwise false */ public boolean shouldSkipClass(Class clazz); } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/FieldAttributes.java000066400000000000000000000110021316034351600272570ustar00rootroot00000000000000/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson; import com.google.gson.internal.$Gson$Preconditions; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Type; import java.util.Arrays; import java.util.Collection; /** * A data object that stores attributes of a field. * *

This class is immutable; therefore, it can be safely shared across threads. * * @author Inderjeet Singh * @author Joel Leitch * * @since 1.4 */ public final class FieldAttributes { private final Field field; /** * Constructs a Field Attributes object from the {@code f}. * * @param f the field to pull attributes from */ public FieldAttributes(Field f) { $Gson$Preconditions.checkNotNull(f); this.field = f; } /** * @return the declaring class that contains this field */ public Class getDeclaringClass() { return field.getDeclaringClass(); } /** * @return the name of the field */ public String getName() { return field.getName(); } /** *

For example, assume the following class definition: *

   * public class Foo {
   *   private String bar;
   *   private List<String> red;
   * }
   *
   * Type listParameterizedType = new TypeToken<List<String>>() {}.getType();
   * 
* *

This method would return {@code String.class} for the {@code bar} field and * {@code listParameterizedType} for the {@code red} field. * * @return the specific type declared for this field */ public Type getDeclaredType() { return field.getGenericType(); } /** * Returns the {@code Class} object that was declared for this field. * *

For example, assume the following class definition: *

   * public class Foo {
   *   private String bar;
   *   private List<String> red;
   * }
   * 
* *

This method would return {@code String.class} for the {@code bar} field and * {@code List.class} for the {@code red} field. * * @return the specific class object that was declared for the field */ public Class getDeclaredClass() { return field.getType(); } /** * Return the {@code T} annotation object from this field if it exist; otherwise returns * {@code null}. * * @param annotation the class of the annotation that will be retrieved * @return the annotation instance if it is bound to the field; otherwise {@code null} */ public T getAnnotation(Class annotation) { return field.getAnnotation(annotation); } /** * Return the annotations that are present on this field. * * @return an array of all the annotations set on the field * @since 1.4 */ public Collection getAnnotations() { return Arrays.asList(field.getAnnotations()); } /** * Returns {@code true} if the field is defined with the {@code modifier}. * *

This method is meant to be called as: *

   * boolean hasPublicModifier = fieldAttribute.hasModifier(java.lang.reflect.Modifier.PUBLIC);
   * 
* * @see java.lang.reflect.Modifier */ public boolean hasModifier(int modifier) { return (field.getModifiers() & modifier) != 0; } /** * Returns the value of the field represented by this {@code Field}, on * the specified object. The value is automatically wrapped in an * object if it has a primitive type. * * @return the value of the represented field in object * {@code obj}; primitive values are wrapped in an appropriate * object before being returned * @throws IllegalAccessException * @throws IllegalArgumentException */ Object get(Object instance) throws IllegalAccessException { return field.get(instance); } /** * This is exposed internally only for the removing synthetic fields from the JSON output. * * @return true if the field is synthetic; otherwise false */ boolean isSynthetic() { return field.isSynthetic(); } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/FieldNamingPolicy.java000066400000000000000000000132141316034351600275310ustar00rootroot00000000000000/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson; import java.lang.reflect.Field; import java.util.Locale; /** * An enumeration that defines a few standard naming conventions for JSON field names. * This enumeration should be used in conjunction with {@link com.google.gson.GsonBuilder} * to configure a {@link com.google.gson.Gson} instance to properly translate Java field * names into the desired JSON field names. * * @author Inderjeet Singh * @author Joel Leitch */ public enum FieldNamingPolicy implements FieldNamingStrategy { /** * Using this naming policy with Gson will ensure that the field name is * unchanged. */ IDENTITY() { @Override public String translateName(Field f) { return f.getName(); } }, /** * Using this naming policy with Gson will ensure that the first "letter" of the Java * field name is capitalized when serialized to its JSON form. * *

Here's a few examples of the form "Java Field Name" ---> "JSON Field Name":

*
    *
  • someFieldName ---> SomeFieldName
  • *
  • _someFieldName ---> _SomeFieldName
  • *
*/ UPPER_CAMEL_CASE() { @Override public String translateName(Field f) { return upperCaseFirstLetter(f.getName()); } }, /** * Using this naming policy with Gson will ensure that the first "letter" of the Java * field name is capitalized when serialized to its JSON form and the words will be * separated by a space. * *

Here's a few examples of the form "Java Field Name" ---> "JSON Field Name":

*
    *
  • someFieldName ---> Some Field Name
  • *
  • _someFieldName ---> _Some Field Name
  • *
* * @since 1.4 */ UPPER_CAMEL_CASE_WITH_SPACES() { @Override public String translateName(Field f) { return upperCaseFirstLetter(separateCamelCase(f.getName(), " ")); } }, /** * Using this naming policy with Gson will modify the Java Field name from its camel cased * form to a lower case field name where each word is separated by an underscore (_). * *

Here's a few examples of the form "Java Field Name" ---> "JSON Field Name":

*
    *
  • someFieldName ---> some_field_name
  • *
  • _someFieldName ---> _some_field_name
  • *
  • aStringField ---> a_string_field
  • *
  • aURL ---> a_u_r_l
  • *
*/ LOWER_CASE_WITH_UNDERSCORES() { @Override public String translateName(Field f) { return separateCamelCase(f.getName(), "_").toLowerCase(Locale.ENGLISH); } }, /** * Using this naming policy with Gson will modify the Java Field name from its camel cased * form to a lower case field name where each word is separated by a dash (-). * *

Here's a few examples of the form "Java Field Name" ---> "JSON Field Name":

*
    *
  • someFieldName ---> some-field-name
  • *
  • _someFieldName ---> _some-field-name
  • *
  • aStringField ---> a-string-field
  • *
  • aURL ---> a-u-r-l
  • *
* Using dashes in JavaScript is not recommended since dash is also used for a minus sign in * expressions. This requires that a field named with dashes is always accessed as a quoted * property like {@code myobject['my-field']}. Accessing it as an object field * {@code myobject.my-field} will result in an unintended javascript expression. * @since 1.4 */ LOWER_CASE_WITH_DASHES() { @Override public String translateName(Field f) { return separateCamelCase(f.getName(), "-").toLowerCase(Locale.ENGLISH); } }; /** * Converts the field name that uses camel-case define word separation into * separate words that are separated by the provided {@code separatorString}. */ static String separateCamelCase(String name, String separator) { StringBuilder translation = new StringBuilder(); for (int i = 0, length = name.length(); i < length; i++) { char character = name.charAt(i); if (Character.isUpperCase(character) && translation.length() != 0) { translation.append(separator); } translation.append(character); } return translation.toString(); } /** * Ensures the JSON field names begins with an upper case letter. */ static String upperCaseFirstLetter(String name) { StringBuilder fieldNameBuilder = new StringBuilder(); int index = 0; char firstCharacter = name.charAt(index); int length = name.length(); while (index < length - 1) { if (Character.isLetter(firstCharacter)) { break; } fieldNameBuilder.append(firstCharacter); firstCharacter = name.charAt(++index); } if (!Character.isUpperCase(firstCharacter)) { String modifiedTarget = modifyString(Character.toUpperCase(firstCharacter), name, ++index); return fieldNameBuilder.append(modifiedTarget).toString(); } else { return name; } } private static String modifyString(char firstCharacter, String srcString, int indexOfSubstring) { return (indexOfSubstring < srcString.length()) ? firstCharacter + srcString.substring(indexOfSubstring) : String.valueOf(firstCharacter); } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/FieldNamingStrategy.java000066400000000000000000000024131316034351600300730ustar00rootroot00000000000000/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson; import java.lang.reflect.Field; /** * A mechanism for providing custom field naming in Gson. This allows the client code to translate * field names into a particular convention that is not supported as a normal Java field * declaration rules. For example, Java does not support "-" characters in a field name. * * @author Inderjeet Singh * @author Joel Leitch * @since 1.3 */ public interface FieldNamingStrategy { /** * Translates the field name into its JSON field name representation. * * @param f the field object that we are translating * @return the translated field name. * @since 1.3 */ public String translateName(Field f); } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/Gson.java000066400000000000000000001242061316034351600251060ustar00rootroot00000000000000/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson; import java.io.EOFException; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.Type; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLongArray; import com.google.gson.internal.ConstructorConstructor; import com.google.gson.internal.Excluder; import com.google.gson.internal.Primitives; import com.google.gson.internal.Streams; import com.google.gson.internal.bind.ArrayTypeAdapter; import com.google.gson.internal.bind.CollectionTypeAdapterFactory; import com.google.gson.internal.bind.DateTypeAdapter; import com.google.gson.internal.bind.JsonAdapterAnnotationTypeAdapterFactory; import com.google.gson.internal.bind.JsonTreeReader; import com.google.gson.internal.bind.JsonTreeWriter; import com.google.gson.internal.bind.MapTypeAdapterFactory; import com.google.gson.internal.bind.ObjectTypeAdapter; import com.google.gson.internal.bind.ReflectiveTypeAdapterFactory; import com.google.gson.internal.bind.SqlDateTypeAdapter; import com.google.gson.internal.bind.TimeTypeAdapter; import com.google.gson.internal.bind.TypeAdapters; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import com.google.gson.stream.MalformedJsonException; /** * This is the main class for using Gson. Gson is typically used by first constructing a * Gson instance and then invoking {@link #toJson(Object)} or {@link #fromJson(String, Class)} * methods on it. Gson instances are Thread-safe so you can reuse them freely across multiple * threads. * *

You can create a Gson instance by invoking {@code new Gson()} if the default configuration * is all you need. You can also use {@link GsonBuilder} to build a Gson instance with various * configuration options such as versioning support, pretty printing, custom * {@link JsonSerializer}s, {@link JsonDeserializer}s, and {@link InstanceCreator}s.

* *

Here is an example of how Gson is used for a simple Class: * *

 * Gson gson = new Gson(); // Or use new GsonBuilder().create();
 * MyType target = new MyType();
 * String json = gson.toJson(target); // serializes target to Json
 * MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2
 * 

* *

If the object that your are serializing/deserializing is a {@code ParameterizedType} * (i.e. contains at least one type parameter and may be an array) then you must use the * {@link #toJson(Object, Type)} or {@link #fromJson(String, Type)} method. Here is an * example for serializing and deserializing a {@code ParameterizedType}: * *

 * Type listType = new TypeToken<List<String>>() {}.getType();
 * List<String> target = new LinkedList<String>();
 * target.add("blah");
 *
 * Gson gson = new Gson();
 * String json = gson.toJson(target, listType);
 * List<String> target2 = gson.fromJson(json, listType);
 * 

* *

See the Gson User Guide * for a more complete set of examples.

* * @see com.google.gson.reflect.TypeToken * * @author Inderjeet Singh * @author Joel Leitch * @author Jesse Wilson */ public final class Gson { static final boolean DEFAULT_JSON_NON_EXECUTABLE = false; static final boolean DEFAULT_LENIENT = false; static final boolean DEFAULT_PRETTY_PRINT = false; static final boolean DEFAULT_ESCAPE_HTML = true; static final boolean DEFAULT_SERIALIZE_NULLS = false; static final boolean DEFAULT_COMPLEX_MAP_KEYS = false; static final boolean DEFAULT_SPECIALIZE_FLOAT_VALUES = false; private static final TypeToken NULL_KEY_SURROGATE = TypeToken.get(Object.class); private static final String JSON_NON_EXECUTABLE_PREFIX = ")]}'\n"; /** * This thread local guards against reentrant calls to getAdapter(). In * certain object graphs, creating an adapter for a type may recursively * require an adapter for the same type! Without intervention, the recursive * lookup would stack overflow. We cheat by returning a proxy type adapter. * The proxy is wired up once the initial adapter has been created. */ private final ThreadLocal, FutureTypeAdapter>> calls = new ThreadLocal, FutureTypeAdapter>>(); private final Map, TypeAdapter> typeTokenCache = new ConcurrentHashMap, TypeAdapter>(); private final List factories; private final ConstructorConstructor constructorConstructor; private final Excluder excluder; private final FieldNamingStrategy fieldNamingStrategy; private final boolean serializeNulls; private final boolean htmlSafe; private final boolean generateNonExecutableJson; private final boolean prettyPrinting; private final boolean lenient; private final JsonAdapterAnnotationTypeAdapterFactory jsonAdapterFactory; /** * Constructs a Gson object with default configuration. The default configuration has the * following settings: *
    *
  • The JSON generated by toJson methods is in compact representation. This * means that all the unneeded white-space is removed. You can change this behavior with * {@link GsonBuilder#setPrettyPrinting()}.
  • *
  • The generated JSON omits all the fields that are null. Note that nulls in arrays are * kept as is since an array is an ordered list. Moreover, if a field is not null, but its * generated JSON is empty, the field is kept. You can configure Gson to serialize null values * by setting {@link GsonBuilder#serializeNulls()}.
  • *
  • Gson provides default serialization and deserialization for Enums, {@link Map}, * {@link java.net.URL}, {@link java.net.URI}, {@link java.util.Locale}, {@link java.util.Date}, * {@link java.math.BigDecimal}, and {@link java.math.BigInteger} classes. If you would prefer * to change the default representation, you can do so by registering a type adapter through * {@link GsonBuilder#registerTypeAdapter(Type, Object)}.
  • *
  • The default Date format is same as {@link java.text.DateFormat#DEFAULT}. This format * ignores the millisecond portion of the date during serialization. You can change * this by invoking {@link GsonBuilder#setDateFormat(int)} or * {@link GsonBuilder#setDateFormat(String)}.
  • *
  • By default, Gson ignores the {@link com.google.gson.annotations.Expose} annotation. * You can enable Gson to serialize/deserialize only those fields marked with this annotation * through {@link GsonBuilder#excludeFieldsWithoutExposeAnnotation()}.
  • *
  • By default, Gson ignores the {@link com.google.gson.annotations.Since} annotation. You * can enable Gson to use this annotation through {@link GsonBuilder#setVersion(double)}.
  • *
  • The default field naming policy for the output Json is same as in Java. So, a Java class * field versionNumber will be output as "versionNumber" in * Json. The same rules are applied for mapping incoming Json to the Java classes. You can * change this policy through {@link GsonBuilder#setFieldNamingPolicy(FieldNamingPolicy)}.
  • *
  • By default, Gson excludes transient or static fields from * consideration for serialization and deserialization. You can change this behavior through * {@link GsonBuilder#excludeFieldsWithModifiers(int...)}.
  • *
*/ public Gson() { this(Excluder.DEFAULT, FieldNamingPolicy.IDENTITY, Collections.>emptyMap(), DEFAULT_SERIALIZE_NULLS, DEFAULT_COMPLEX_MAP_KEYS, DEFAULT_JSON_NON_EXECUTABLE, DEFAULT_ESCAPE_HTML, DEFAULT_PRETTY_PRINT, DEFAULT_LENIENT, DEFAULT_SPECIALIZE_FLOAT_VALUES, LongSerializationPolicy.DEFAULT, Collections.emptyList()); } Gson(final Excluder excluder, final FieldNamingStrategy fieldNamingStrategy, final Map> instanceCreators, boolean serializeNulls, boolean complexMapKeySerialization, boolean generateNonExecutableGson, boolean htmlSafe, boolean prettyPrinting, boolean lenient, boolean serializeSpecialFloatingPointValues, LongSerializationPolicy longSerializationPolicy, List typeAdapterFactories) { this.constructorConstructor = new ConstructorConstructor(instanceCreators); this.excluder = excluder; this.fieldNamingStrategy = fieldNamingStrategy; this.serializeNulls = serializeNulls; this.generateNonExecutableJson = generateNonExecutableGson; this.htmlSafe = htmlSafe; this.prettyPrinting = prettyPrinting; this.lenient = lenient; List factories = new ArrayList(); // built-in type adapters that cannot be overridden factories.add(TypeAdapters.JSON_ELEMENT_FACTORY); factories.add(ObjectTypeAdapter.FACTORY); // the excluder must precede all adapters that handle user-defined types factories.add(excluder); // user's type adapters factories.addAll(typeAdapterFactories); // type adapters for basic platform types factories.add(TypeAdapters.STRING_FACTORY); factories.add(TypeAdapters.INTEGER_FACTORY); factories.add(TypeAdapters.BOOLEAN_FACTORY); factories.add(TypeAdapters.BYTE_FACTORY); factories.add(TypeAdapters.SHORT_FACTORY); TypeAdapter longAdapter = longAdapter(longSerializationPolicy); factories.add(TypeAdapters.newFactory(long.class, Long.class, longAdapter)); factories.add(TypeAdapters.newFactory(double.class, Double.class, doubleAdapter(serializeSpecialFloatingPointValues))); factories.add(TypeAdapters.newFactory(float.class, Float.class, floatAdapter(serializeSpecialFloatingPointValues))); factories.add(TypeAdapters.NUMBER_FACTORY); factories.add(TypeAdapters.ATOMIC_INTEGER_FACTORY); factories.add(TypeAdapters.ATOMIC_BOOLEAN_FACTORY); factories.add(TypeAdapters.newFactory(AtomicLong.class, atomicLongAdapter(longAdapter))); factories.add(TypeAdapters.newFactory(AtomicLongArray.class, atomicLongArrayAdapter(longAdapter))); factories.add(TypeAdapters.ATOMIC_INTEGER_ARRAY_FACTORY); factories.add(TypeAdapters.CHARACTER_FACTORY); factories.add(TypeAdapters.STRING_BUILDER_FACTORY); factories.add(TypeAdapters.STRING_BUFFER_FACTORY); factories.add(TypeAdapters.newFactory(BigDecimal.class, TypeAdapters.BIG_DECIMAL)); factories.add(TypeAdapters.newFactory(BigInteger.class, TypeAdapters.BIG_INTEGER)); factories.add(TypeAdapters.URL_FACTORY); factories.add(TypeAdapters.URI_FACTORY); factories.add(TypeAdapters.UUID_FACTORY); factories.add(TypeAdapters.CURRENCY_FACTORY); factories.add(TypeAdapters.LOCALE_FACTORY); factories.add(TypeAdapters.INET_ADDRESS_FACTORY); factories.add(TypeAdapters.BIT_SET_FACTORY); factories.add(DateTypeAdapter.FACTORY); factories.add(TypeAdapters.CALENDAR_FACTORY); factories.add(TimeTypeAdapter.FACTORY); factories.add(SqlDateTypeAdapter.FACTORY); factories.add(TypeAdapters.TIMESTAMP_FACTORY); factories.add(ArrayTypeAdapter.FACTORY); factories.add(TypeAdapters.CLASS_FACTORY); // type adapters for composite and user-defined types factories.add(new CollectionTypeAdapterFactory(constructorConstructor)); factories.add(new MapTypeAdapterFactory(constructorConstructor, complexMapKeySerialization)); this.jsonAdapterFactory = new JsonAdapterAnnotationTypeAdapterFactory(constructorConstructor); factories.add(jsonAdapterFactory); factories.add(TypeAdapters.ENUM_FACTORY); factories.add(new ReflectiveTypeAdapterFactory( constructorConstructor, fieldNamingStrategy, excluder, jsonAdapterFactory)); this.factories = Collections.unmodifiableList(factories); } public Excluder excluder() { return excluder; } public FieldNamingStrategy fieldNamingStrategy() { return fieldNamingStrategy; } public boolean serializeNulls() { return serializeNulls; } public boolean htmlSafe() { return htmlSafe; } private TypeAdapter doubleAdapter(boolean serializeSpecialFloatingPointValues) { if (serializeSpecialFloatingPointValues) { return TypeAdapters.DOUBLE; } return new TypeAdapter() { @Override public Double read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } return in.nextDouble(); } @Override public void write(JsonWriter out, Number value) throws IOException { if (value == null) { out.nullValue(); return; } double doubleValue = value.doubleValue(); checkValidFloatingPoint(doubleValue); out.value(value); } }; } private TypeAdapter floatAdapter(boolean serializeSpecialFloatingPointValues) { if (serializeSpecialFloatingPointValues) { return TypeAdapters.FLOAT; } return new TypeAdapter() { @Override public Float read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } return (float) in.nextDouble(); } @Override public void write(JsonWriter out, Number value) throws IOException { if (value == null) { out.nullValue(); return; } float floatValue = value.floatValue(); checkValidFloatingPoint(floatValue); out.value(value); } }; } static void checkValidFloatingPoint(double value) { if (Double.isNaN(value) || Double.isInfinite(value)) { throw new IllegalArgumentException(value + " is not a valid double value as per JSON specification. To override this" + " behavior, use GsonBuilder.serializeSpecialFloatingPointValues() method."); } } private static TypeAdapter longAdapter(LongSerializationPolicy longSerializationPolicy) { if (longSerializationPolicy == LongSerializationPolicy.DEFAULT) { return TypeAdapters.LONG; } return new TypeAdapter() { @Override public Number read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } return in.nextLong(); } @Override public void write(JsonWriter out, Number value) throws IOException { if (value == null) { out.nullValue(); return; } out.value(value.toString()); } }; } private static TypeAdapter atomicLongAdapter(final TypeAdapter longAdapter) { return new TypeAdapter() { @Override public void write(JsonWriter out, AtomicLong value) throws IOException { longAdapter.write(out, value.get()); } @Override public AtomicLong read(JsonReader in) throws IOException { Number value = longAdapter.read(in); return new AtomicLong(value.longValue()); } }.nullSafe(); } private static TypeAdapter atomicLongArrayAdapter(final TypeAdapter longAdapter) { return new TypeAdapter() { @Override public void write(JsonWriter out, AtomicLongArray value) throws IOException { out.beginArray(); for (int i = 0, length = value.length(); i < length; i++) { longAdapter.write(out, value.get(i)); } out.endArray(); } @Override public AtomicLongArray read(JsonReader in) throws IOException { List list = new ArrayList(); in.beginArray(); while (in.hasNext()) { long value = longAdapter.read(in).longValue(); list.add(value); } in.endArray(); int length = list.size(); AtomicLongArray array = new AtomicLongArray(length); for (int i = 0; i < length; ++i) { array.set(i, list.get(i)); } return array; } }.nullSafe(); } /** * Returns the type adapter for {@code} type. * * @throws IllegalArgumentException if this GSON cannot serialize and * deserialize {@code type}. */ @SuppressWarnings("unchecked") public TypeAdapter getAdapter(TypeToken type) { TypeAdapter cached = typeTokenCache.get(type == null ? NULL_KEY_SURROGATE : type); if (cached != null) { return (TypeAdapter) cached; } Map, FutureTypeAdapter> threadCalls = calls.get(); boolean requiresThreadLocalCleanup = false; if (threadCalls == null) { threadCalls = new HashMap, FutureTypeAdapter>(); calls.set(threadCalls); requiresThreadLocalCleanup = true; } // the key and value type parameters always agree FutureTypeAdapter ongoingCall = (FutureTypeAdapter) threadCalls.get(type); if (ongoingCall != null) { return ongoingCall; } try { FutureTypeAdapter call = new FutureTypeAdapter(); threadCalls.put(type, call); for (TypeAdapterFactory factory : factories) { TypeAdapter candidate = factory.create(this, type); if (candidate != null) { call.setDelegate(candidate); typeTokenCache.put(type, candidate); return candidate; } } throw new IllegalArgumentException("GSON cannot handle " + type); } finally { threadCalls.remove(type); if (requiresThreadLocalCleanup) { calls.remove(); } } } /** * This method is used to get an alternate type adapter for the specified type. This is used * to access a type adapter that is overridden by a {@link TypeAdapterFactory} that you * may have registered. This features is typically used when you want to register a type * adapter that does a little bit of work but then delegates further processing to the Gson * default type adapter. Here is an example: *

Let's say we want to write a type adapter that counts the number of objects being read * from or written to JSON. We can achieve this by writing a type adapter factory that uses * the getDelegateAdapter method: *

 {@code
   *  class StatsTypeAdapterFactory implements TypeAdapterFactory {
   *    public int numReads = 0;
   *    public int numWrites = 0;
   *    public  TypeAdapter create(Gson gson, TypeToken type) {
   *      final TypeAdapter delegate = gson.getDelegateAdapter(this, type);
   *      return new TypeAdapter() {
   *        public void write(JsonWriter out, T value) throws IOException {
   *          ++numWrites;
   *          delegate.write(out, value);
   *        }
   *        public T read(JsonReader in) throws IOException {
   *          ++numReads;
   *          return delegate.read(in);
   *        }
   *      };
   *    }
   *  }
   *  } 
* This factory can now be used like this: *
 {@code
   *  StatsTypeAdapterFactory stats = new StatsTypeAdapterFactory();
   *  Gson gson = new GsonBuilder().registerTypeAdapterFactory(stats).create();
   *  // Call gson.toJson() and fromJson methods on objects
   *  System.out.println("Num JSON reads" + stats.numReads);
   *  System.out.println("Num JSON writes" + stats.numWrites);
   *  }
* Note that this call will skip all factories registered before {@code skipPast}. In case of * multiple TypeAdapterFactories registered it is up to the caller of this function to insure * that the order of registration does not prevent this method from reaching a factory they * would expect to reply from this call. * Note that since you can not override type adapter factories for String and Java primitive * types, our stats factory will not count the number of String or primitives that will be * read or written. * @param skipPast The type adapter factory that needs to be skipped while searching for * a matching type adapter. In most cases, you should just pass this (the type adapter * factory from where {@link #getDelegateAdapter} method is being invoked). * @param type Type for which the delegate adapter is being searched for. * * @since 2.2 */ public TypeAdapter getDelegateAdapter(TypeAdapterFactory skipPast, TypeToken type) { // Hack. If the skipPast factory isn't registered, assume the factory is being requested via // our @JsonAdapter annotation. if (!factories.contains(skipPast)) { skipPast = jsonAdapterFactory; } boolean skipPastFound = false; for (TypeAdapterFactory factory : factories) { if (!skipPastFound) { if (factory == skipPast) { skipPastFound = true; } continue; } TypeAdapter candidate = factory.create(this, type); if (candidate != null) { return candidate; } } throw new IllegalArgumentException("GSON cannot serialize " + type); } /** * Returns the type adapter for {@code} type. * * @throws IllegalArgumentException if this GSON cannot serialize and * deserialize {@code type}. */ public TypeAdapter getAdapter(Class type) { return getAdapter(TypeToken.get(type)); } /** * This method serializes the specified object into its equivalent representation as a tree of * {@link JsonElement}s. This method should be used when the specified object is not a generic * type. This method uses {@link Class#getClass()} to get the type for the specified object, but * the {@code getClass()} loses the generic type information because of the Type Erasure feature * of Java. Note that this method works fine if the any of the object fields are of generic type, * just the object itself should not be of a generic type. If the object is of generic type, use * {@link #toJsonTree(Object, Type)} instead. * * @param src the object for which Json representation is to be created setting for Gson * @return Json representation of {@code src}. * @since 1.4 */ public JsonElement toJsonTree(Object src) { if (src == null) { return JsonNull.INSTANCE; } return toJsonTree(src, src.getClass()); } /** * This method serializes the specified object, including those of generic types, into its * equivalent representation as a tree of {@link JsonElement}s. This method must be used if the * specified object is a generic type. For non-generic objects, use {@link #toJsonTree(Object)} * instead. * * @param src the object for which JSON representation is to be created * @param typeOfSrc The specific genericized type of src. You can obtain * this type by using the {@link com.google.gson.reflect.TypeToken} class. For example, * to get the type for {@code Collection}, you should use: *
   * Type typeOfSrc = new TypeToken<Collection<Foo>>(){}.getType();
   * 
* @return Json representation of {@code src} * @since 1.4 */ public JsonElement toJsonTree(Object src, Type typeOfSrc) { JsonTreeWriter writer = new JsonTreeWriter(); toJson(src, typeOfSrc, writer); return writer.get(); } /** * This method serializes the specified object into its equivalent Json representation. * This method should be used when the specified object is not a generic type. This method uses * {@link Class#getClass()} to get the type for the specified object, but the * {@code getClass()} loses the generic type information because of the Type Erasure feature * of Java. Note that this method works fine if the any of the object fields are of generic type, * just the object itself should not be of a generic type. If the object is of generic type, use * {@link #toJson(Object, Type)} instead. If you want to write out the object to a * {@link Writer}, use {@link #toJson(Object, Appendable)} instead. * * @param src the object for which Json representation is to be created setting for Gson * @return Json representation of {@code src}. */ public String toJson(Object src) { if (src == null) { return toJson(JsonNull.INSTANCE); } return toJson(src, src.getClass()); } /** * This method serializes the specified object, including those of generic types, into its * equivalent Json representation. This method must be used if the specified object is a generic * type. For non-generic objects, use {@link #toJson(Object)} instead. If you want to write out * the object to a {@link Appendable}, use {@link #toJson(Object, Type, Appendable)} instead. * * @param src the object for which JSON representation is to be created * @param typeOfSrc The specific genericized type of src. You can obtain * this type by using the {@link com.google.gson.reflect.TypeToken} class. For example, * to get the type for {@code Collection}, you should use: *
   * Type typeOfSrc = new TypeToken<Collection<Foo>>(){}.getType();
   * 
* @return Json representation of {@code src} */ public String toJson(Object src, Type typeOfSrc) { StringWriter writer = new StringWriter(); toJson(src, typeOfSrc, writer); return writer.toString(); } /** * This method serializes the specified object into its equivalent Json representation. * This method should be used when the specified object is not a generic type. This method uses * {@link Class#getClass()} to get the type for the specified object, but the * {@code getClass()} loses the generic type information because of the Type Erasure feature * of Java. Note that this method works fine if the any of the object fields are of generic type, * just the object itself should not be of a generic type. If the object is of generic type, use * {@link #toJson(Object, Type, Appendable)} instead. * * @param src the object for which Json representation is to be created setting for Gson * @param writer Writer to which the Json representation needs to be written * @throws JsonIOException if there was a problem writing to the writer * @since 1.2 */ public void toJson(Object src, Appendable writer) throws JsonIOException { if (src != null) { toJson(src, src.getClass(), writer); } else { toJson(JsonNull.INSTANCE, writer); } } /** * This method serializes the specified object, including those of generic types, into its * equivalent Json representation. This method must be used if the specified object is a generic * type. For non-generic objects, use {@link #toJson(Object, Appendable)} instead. * * @param src the object for which JSON representation is to be created * @param typeOfSrc The specific genericized type of src. You can obtain * this type by using the {@link com.google.gson.reflect.TypeToken} class. For example, * to get the type for {@code Collection}, you should use: *
   * Type typeOfSrc = new TypeToken<Collection<Foo>>(){}.getType();
   * 
* @param writer Writer to which the Json representation of src needs to be written. * @throws JsonIOException if there was a problem writing to the writer * @since 1.2 */ public void toJson(Object src, Type typeOfSrc, Appendable writer) throws JsonIOException { try { JsonWriter jsonWriter = newJsonWriter(Streams.writerForAppendable(writer)); toJson(src, typeOfSrc, jsonWriter); } catch (IOException e) { throw new JsonIOException(e); } } /** * Writes the JSON representation of {@code src} of type {@code typeOfSrc} to * {@code writer}. * @throws JsonIOException if there was a problem writing to the writer */ @SuppressWarnings("unchecked") public void toJson(Object src, Type typeOfSrc, JsonWriter writer) throws JsonIOException { TypeAdapter adapter = getAdapter(TypeToken.get(typeOfSrc)); boolean oldLenient = writer.isLenient(); writer.setLenient(true); boolean oldHtmlSafe = writer.isHtmlSafe(); writer.setHtmlSafe(htmlSafe); boolean oldSerializeNulls = writer.getSerializeNulls(); writer.setSerializeNulls(serializeNulls); try { ((TypeAdapter) adapter).write(writer, src); } catch (IOException e) { throw new JsonIOException(e); } finally { writer.setLenient(oldLenient); writer.setHtmlSafe(oldHtmlSafe); writer.setSerializeNulls(oldSerializeNulls); } } /** * Converts a tree of {@link JsonElement}s into its equivalent JSON representation. * * @param jsonElement root of a tree of {@link JsonElement}s * @return JSON String representation of the tree * @since 1.4 */ public String toJson(JsonElement jsonElement) { StringWriter writer = new StringWriter(); toJson(jsonElement, writer); return writer.toString(); } /** * Writes out the equivalent JSON for a tree of {@link JsonElement}s. * * @param jsonElement root of a tree of {@link JsonElement}s * @param writer Writer to which the Json representation needs to be written * @throws JsonIOException if there was a problem writing to the writer * @since 1.4 */ public void toJson(JsonElement jsonElement, Appendable writer) throws JsonIOException { try { JsonWriter jsonWriter = newJsonWriter(Streams.writerForAppendable(writer)); toJson(jsonElement, jsonWriter); } catch (IOException e) { throw new JsonIOException(e); } } /** * Returns a new JSON writer configured for the settings on this Gson instance. */ public JsonWriter newJsonWriter(Writer writer) throws IOException { if (generateNonExecutableJson) { writer.write(JSON_NON_EXECUTABLE_PREFIX); } JsonWriter jsonWriter = new JsonWriter(writer); if (prettyPrinting) { jsonWriter.setIndent(" "); } jsonWriter.setSerializeNulls(serializeNulls); return jsonWriter; } /** * Returns a new JSON reader configured for the settings on this Gson instance. */ public JsonReader newJsonReader(Reader reader) { JsonReader jsonReader = new JsonReader(reader); jsonReader.setLenient(lenient); return jsonReader; } /** * Writes the JSON for {@code jsonElement} to {@code writer}. * @throws JsonIOException if there was a problem writing to the writer */ public void toJson(JsonElement jsonElement, JsonWriter writer) throws JsonIOException { boolean oldLenient = writer.isLenient(); writer.setLenient(true); boolean oldHtmlSafe = writer.isHtmlSafe(); writer.setHtmlSafe(htmlSafe); boolean oldSerializeNulls = writer.getSerializeNulls(); writer.setSerializeNulls(serializeNulls); try { Streams.write(jsonElement, writer); } catch (IOException e) { throw new JsonIOException(e); } finally { writer.setLenient(oldLenient); writer.setHtmlSafe(oldHtmlSafe); writer.setSerializeNulls(oldSerializeNulls); } } /** * This method deserializes the specified Json into an object of the specified class. It is not * suitable to use if the specified class is a generic type since it will not have the generic * type information because of the Type Erasure feature of Java. Therefore, this method should not * be used if the desired type is a generic type. Note that this method works fine if the any of * the fields of the specified object are generics, just the object itself should not be a * generic type. For the cases when the object is of generic type, invoke * {@link #fromJson(String, Type)}. If you have the Json in a {@link Reader} instead of * a String, use {@link #fromJson(Reader, Class)} instead. * * @param the type of the desired object * @param json the string from which the object is to be deserialized * @param classOfT the class of T * @return an object of type T from the string. Returns {@code null} if {@code json} is {@code null} * or if {@code json} is empty. * @throws JsonSyntaxException if json is not a valid representation for an object of type * classOfT */ public T fromJson(String json, Class classOfT) throws JsonSyntaxException { Object object = fromJson(json, (Type) classOfT); return Primitives.wrap(classOfT).cast(object); } /** * This method deserializes the specified Json into an object of the specified type. This method * is useful if the specified object is a generic type. For non-generic objects, use * {@link #fromJson(String, Class)} instead. If you have the Json in a {@link Reader} instead of * a String, use {@link #fromJson(Reader, Type)} instead. * * @param the type of the desired object * @param json the string from which the object is to be deserialized * @param typeOfT The specific genericized type of src. You can obtain this type by using the * {@link com.google.gson.reflect.TypeToken} class. For example, to get the type for * {@code Collection}, you should use: *
   * Type typeOfT = new TypeToken<Collection<Foo>>(){}.getType();
   * 
* @return an object of type T from the string. Returns {@code null} if {@code json} is {@code null}. * @throws JsonParseException if json is not a valid representation for an object of type typeOfT * @throws JsonSyntaxException if json is not a valid representation for an object of type */ @SuppressWarnings("unchecked") public T fromJson(String json, Type typeOfT) throws JsonSyntaxException { if (json == null) { return null; } StringReader reader = new StringReader(json); T target = (T) fromJson(reader, typeOfT); return target; } /** * This method deserializes the Json read from the specified reader into an object of the * specified class. It is not suitable to use if the specified class is a generic type since it * will not have the generic type information because of the Type Erasure feature of Java. * Therefore, this method should not be used if the desired type is a generic type. Note that * this method works fine if the any of the fields of the specified object are generics, just the * object itself should not be a generic type. For the cases when the object is of generic type, * invoke {@link #fromJson(Reader, Type)}. If you have the Json in a String form instead of a * {@link Reader}, use {@link #fromJson(String, Class)} instead. * * @param the type of the desired object * @param json the reader producing the Json from which the object is to be deserialized. * @param classOfT the class of T * @return an object of type T from the string. Returns {@code null} if {@code json} is at EOF. * @throws JsonIOException if there was a problem reading from the Reader * @throws JsonSyntaxException if json is not a valid representation for an object of type * @since 1.2 */ public T fromJson(Reader json, Class classOfT) throws JsonSyntaxException, JsonIOException { JsonReader jsonReader = newJsonReader(json); Object object = fromJson(jsonReader, classOfT); assertFullConsumption(object, jsonReader); return Primitives.wrap(classOfT).cast(object); } /** * This method deserializes the Json read from the specified reader into an object of the * specified type. This method is useful if the specified object is a generic type. For * non-generic objects, use {@link #fromJson(Reader, Class)} instead. If you have the Json in a * String form instead of a {@link Reader}, use {@link #fromJson(String, Type)} instead. * * @param the type of the desired object * @param json the reader producing Json from which the object is to be deserialized * @param typeOfT The specific genericized type of src. You can obtain this type by using the * {@link com.google.gson.reflect.TypeToken} class. For example, to get the type for * {@code Collection}, you should use: *
   * Type typeOfT = new TypeToken<Collection<Foo>>(){}.getType();
   * 
* @return an object of type T from the json. Returns {@code null} if {@code json} is at EOF. * @throws JsonIOException if there was a problem reading from the Reader * @throws JsonSyntaxException if json is not a valid representation for an object of type * @since 1.2 */ @SuppressWarnings("unchecked") public T fromJson(Reader json, Type typeOfT) throws JsonIOException, JsonSyntaxException { JsonReader jsonReader = newJsonReader(json); T object = (T) fromJson(jsonReader, typeOfT); assertFullConsumption(object, jsonReader); return object; } private static void assertFullConsumption(Object obj, JsonReader reader) { try { if (obj != null && reader.peek() != JsonToken.END_DOCUMENT) { throw new JsonIOException("JSON document was not fully consumed."); } } catch (MalformedJsonException e) { throw new JsonSyntaxException(e); } catch (IOException e) { throw new JsonIOException(e); } } /** * Reads the next JSON value from {@code reader} and convert it to an object * of type {@code typeOfT}. Returns {@code null}, if the {@code reader} is at EOF. * Since Type is not parameterized by T, this method is type unsafe and should be used carefully * * @throws JsonIOException if there was a problem writing to the Reader * @throws JsonSyntaxException if json is not a valid representation for an object of type */ @SuppressWarnings("unchecked") public T fromJson(JsonReader reader, Type typeOfT) throws JsonIOException, JsonSyntaxException { boolean isEmpty = true; boolean oldLenient = reader.isLenient(); reader.setLenient(true); try { reader.peek(); isEmpty = false; TypeToken typeToken = (TypeToken) TypeToken.get(typeOfT); TypeAdapter typeAdapter = getAdapter(typeToken); T object = typeAdapter.read(reader); return object; } catch (EOFException e) { /* * For compatibility with JSON 1.5 and earlier, we return null for empty * documents instead of throwing. */ if (isEmpty) { return null; } throw new JsonSyntaxException(e); } catch (IllegalStateException e) { throw new JsonSyntaxException(e); } catch (IOException e) { // TODO(inder): Figure out whether it is indeed right to rethrow this as JsonSyntaxException throw new JsonSyntaxException(e); } finally { reader.setLenient(oldLenient); } } /** * This method deserializes the Json read from the specified parse tree into an object of the * specified type. It is not suitable to use if the specified class is a generic type since it * will not have the generic type information because of the Type Erasure feature of Java. * Therefore, this method should not be used if the desired type is a generic type. Note that * this method works fine if the any of the fields of the specified object are generics, just the * object itself should not be a generic type. For the cases when the object is of generic type, * invoke {@link #fromJson(JsonElement, Type)}. * @param the type of the desired object * @param json the root of the parse tree of {@link JsonElement}s from which the object is to * be deserialized * @param classOfT The class of T * @return an object of type T from the json. Returns {@code null} if {@code json} is {@code null}. * @throws JsonSyntaxException if json is not a valid representation for an object of type typeOfT * @since 1.3 */ public T fromJson(JsonElement json, Class classOfT) throws JsonSyntaxException { Object object = fromJson(json, (Type) classOfT); return Primitives.wrap(classOfT).cast(object); } /** * This method deserializes the Json read from the specified parse tree into an object of the * specified type. This method is useful if the specified object is a generic type. For * non-generic objects, use {@link #fromJson(JsonElement, Class)} instead. * * @param the type of the desired object * @param json the root of the parse tree of {@link JsonElement}s from which the object is to * be deserialized * @param typeOfT The specific genericized type of src. You can obtain this type by using the * {@link com.google.gson.reflect.TypeToken} class. For example, to get the type for * {@code Collection}, you should use: *
   * Type typeOfT = new TypeToken<Collection<Foo>>(){}.getType();
   * 
* @return an object of type T from the json. Returns {@code null} if {@code json} is {@code null}. * @throws JsonSyntaxException if json is not a valid representation for an object of type typeOfT * @since 1.3 */ @SuppressWarnings("unchecked") public T fromJson(JsonElement json, Type typeOfT) throws JsonSyntaxException { if (json == null) { return null; } return (T) fromJson(new JsonTreeReader(json), typeOfT); } static class FutureTypeAdapter extends TypeAdapter { private TypeAdapter delegate; public void setDelegate(TypeAdapter typeAdapter) { if (delegate != null) { throw new AssertionError(); } delegate = typeAdapter; } @Override public T read(JsonReader in) throws IOException { if (delegate == null) { throw new IllegalStateException(); } return delegate.read(in); } @Override public void write(JsonWriter out, T value) throws IOException { if (delegate == null) { throw new IllegalStateException(); } delegate.write(out, value); } } @Override public String toString() { return new StringBuilder("{serializeNulls:") .append(serializeNulls) .append(",factories:").append(factories) .append(",instanceCreators:").append(constructorConstructor) .append("}") .toString(); } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/GsonBuilder.java000066400000000000000000000622561316034351600264230ustar00rootroot00000000000000/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson; import java.lang.reflect.Type; import java.sql.Timestamp; import java.text.DateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import com.google.gson.internal.$Gson$Preconditions; import com.google.gson.internal.Excluder; import com.google.gson.internal.bind.TreeTypeAdapter; import com.google.gson.internal.bind.TypeAdapters; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import static com.google.gson.Gson.DEFAULT_COMPLEX_MAP_KEYS; import static com.google.gson.Gson.DEFAULT_ESCAPE_HTML; import static com.google.gson.Gson.DEFAULT_JSON_NON_EXECUTABLE; import static com.google.gson.Gson.DEFAULT_LENIENT; import static com.google.gson.Gson.DEFAULT_PRETTY_PRINT; import static com.google.gson.Gson.DEFAULT_SERIALIZE_NULLS; import static com.google.gson.Gson.DEFAULT_SPECIALIZE_FLOAT_VALUES; /** *

Use this builder to construct a {@link Gson} instance when you need to set configuration * options other than the default. For {@link Gson} with default configuration, it is simpler to * use {@code new Gson()}. {@code GsonBuilder} is best used by creating it, and then invoking its * various configuration methods, and finally calling create.

* *

The following is an example shows how to use the {@code GsonBuilder} to construct a Gson * instance: * *

 * Gson gson = new GsonBuilder()
 *     .registerTypeAdapter(Id.class, new IdTypeAdapter())
 *     .enableComplexMapKeySerialization()
 *     .serializeNulls()
 *     .setDateFormat(DateFormat.LONG)
 *     .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
 *     .setPrettyPrinting()
 *     .setVersion(1.0)
 *     .create();
 * 

* *

NOTES: *

    *
  • the order of invocation of configuration methods does not matter.
  • *
  • The default serialization of {@link Date} and its subclasses in Gson does * not contain time-zone information. So, if you are using date/time instances, * use {@code GsonBuilder} and its {@code setDateFormat} methods.
  • *
*

* * @author Inderjeet Singh * @author Joel Leitch * @author Jesse Wilson */ public final class GsonBuilder { private Excluder excluder = Excluder.DEFAULT; private LongSerializationPolicy longSerializationPolicy = LongSerializationPolicy.DEFAULT; private FieldNamingStrategy fieldNamingPolicy = FieldNamingPolicy.IDENTITY; private final Map> instanceCreators = new HashMap>(); private final List factories = new ArrayList(); /** tree-style hierarchy factories. These come after factories for backwards compatibility. */ private final List hierarchyFactories = new ArrayList(); private boolean serializeNulls = DEFAULT_SERIALIZE_NULLS; private String datePattern; private int dateStyle = DateFormat.DEFAULT; private int timeStyle = DateFormat.DEFAULT; private boolean complexMapKeySerialization = DEFAULT_COMPLEX_MAP_KEYS; private boolean serializeSpecialFloatingPointValues = DEFAULT_SPECIALIZE_FLOAT_VALUES; private boolean escapeHtmlChars = DEFAULT_ESCAPE_HTML; private boolean prettyPrinting = DEFAULT_PRETTY_PRINT; private boolean generateNonExecutableJson = DEFAULT_JSON_NON_EXECUTABLE; private boolean lenient = DEFAULT_LENIENT; /** * Creates a GsonBuilder instance that can be used to build Gson with various configuration * settings. GsonBuilder follows the builder pattern, and it is typically used by first * invoking various configuration methods to set desired options, and finally calling * {@link #create()}. */ public GsonBuilder() { } /** * Configures Gson to enable versioning support. * * @param ignoreVersionsAfter any field or type marked with a version higher than this value * are ignored during serialization or deserialization. * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern */ public GsonBuilder setVersion(double ignoreVersionsAfter) { excluder = excluder.withVersion(ignoreVersionsAfter); return this; } /** * Configures Gson to excludes all class fields that have the specified modifiers. By default, * Gson will exclude all fields marked transient or static. This method will override that * behavior. * * @param modifiers the field modifiers. You must use the modifiers specified in the * {@link java.lang.reflect.Modifier} class. For example, * {@link java.lang.reflect.Modifier#TRANSIENT}, * {@link java.lang.reflect.Modifier#STATIC}. * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern */ public GsonBuilder excludeFieldsWithModifiers(int... modifiers) { excluder = excluder.withModifiers(modifiers); return this; } /** * Makes the output JSON non-executable in Javascript by prefixing the generated JSON with some * special text. This prevents attacks from third-party sites through script sourcing. See * Gson Issue 42 * for details. * * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern * @since 1.3 */ public GsonBuilder generateNonExecutableJson() { this.generateNonExecutableJson = true; return this; } /** * Configures Gson to exclude all fields from consideration for serialization or deserialization * that do not have the {@link com.google.gson.annotations.Expose} annotation. * * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern */ public GsonBuilder excludeFieldsWithoutExposeAnnotation() { excluder = excluder.excludeFieldsWithoutExposeAnnotation(); return this; } /** * Configure Gson to serialize null fields. By default, Gson omits all fields that are null * during serialization. * * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern * @since 1.2 */ public GsonBuilder serializeNulls() { this.serializeNulls = true; return this; } /** * Enabling this feature will only change the serialized form if the map key is * a complex type (i.e. non-primitive) in its serialized JSON * form. The default implementation of map serialization uses {@code toString()} * on the key; however, when this is called then one of the following cases * apply: * *

Maps as JSON objects

* For this case, assume that a type adapter is registered to serialize and * deserialize some {@code Point} class, which contains an x and y coordinate, * to/from the JSON Primitive string value {@code "(x,y)"}. The Java map would * then be serialized as a {@link JsonObject}. * *

Below is an example: *

  {@code
   *   Gson gson = new GsonBuilder()
   *       .register(Point.class, new MyPointTypeAdapter())
   *       .enableComplexMapKeySerialization()
   *       .create();
   *
   *   Map original = new LinkedHashMap();
   *   original.put(new Point(5, 6), "a");
   *   original.put(new Point(8, 8), "b");
   *   System.out.println(gson.toJson(original, type));
   * }
* The above code prints this JSON object:
  {@code
   *   {
   *     "(5,6)": "a",
   *     "(8,8)": "b"
   *   }
   * }
* *

Maps as JSON arrays

* For this case, assume that a type adapter was NOT registered for some * {@code Point} class, but rather the default Gson serialization is applied. * In this case, some {@code new Point(2,3)} would serialize as {@code * {"x":2,"y":5}}. * *

Given the assumption above, a {@code Map} will be * serialize as an array of arrays (can be viewed as an entry set of pairs). * *

Below is an example of serializing complex types as JSON arrays: *

 {@code
   *   Gson gson = new GsonBuilder()
   *       .enableComplexMapKeySerialization()
   *       .create();
   *
   *   Map original = new LinkedHashMap();
   *   original.put(new Point(5, 6), "a");
   *   original.put(new Point(8, 8), "b");
   *   System.out.println(gson.toJson(original, type));
   * }
   *
   * The JSON output would look as follows:
   * 
   {@code
   *   [
   *     [
   *       {
   *         "x": 5,
   *         "y": 6
   *       },
   *       "a"
   *     ],
   *     [
   *       {
   *         "x": 8,
   *         "y": 8
   *       },
   *       "b"
   *     ]
   *   ]
   * }
* * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern * @since 1.7 */ public GsonBuilder enableComplexMapKeySerialization() { complexMapKeySerialization = true; return this; } /** * Configures Gson to exclude inner classes during serialization. * * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern * @since 1.3 */ public GsonBuilder disableInnerClassSerialization() { excluder = excluder.disableInnerClassSerialization(); return this; } /** * Configures Gson to apply a specific serialization policy for {@code Long} and {@code long} * objects. * * @param serializationPolicy the particular policy to use for serializing longs. * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern * @since 1.3 */ public GsonBuilder setLongSerializationPolicy(LongSerializationPolicy serializationPolicy) { this.longSerializationPolicy = serializationPolicy; return this; } /** * Configures Gson to apply a specific naming policy to an object's field during serialization * and deserialization. * * @param namingConvention the JSON field naming convention to use for serialization and * deserialization. * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern */ public GsonBuilder setFieldNamingPolicy(FieldNamingPolicy namingConvention) { this.fieldNamingPolicy = namingConvention; return this; } /** * Configures Gson to apply a specific naming policy strategy to an object's field during * serialization and deserialization. * * @param fieldNamingStrategy the actual naming strategy to apply to the fields * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern * @since 1.3 */ public GsonBuilder setFieldNamingStrategy(FieldNamingStrategy fieldNamingStrategy) { this.fieldNamingPolicy = fieldNamingStrategy; return this; } /** * Configures Gson to apply a set of exclusion strategies during both serialization and * deserialization. Each of the {@code strategies} will be applied as a disjunction rule. * This means that if one of the {@code strategies} suggests that a field (or class) should be * skipped then that field (or object) is skipped during serialization/deserialization. * * @param strategies the set of strategy object to apply during object (de)serialization. * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern * @since 1.4 */ public GsonBuilder setExclusionStrategies(ExclusionStrategy... strategies) { for (ExclusionStrategy strategy : strategies) { excluder = excluder.withExclusionStrategy(strategy, true, true); } return this; } /** * Configures Gson to apply the passed in exclusion strategy during serialization. * If this method is invoked numerous times with different exclusion strategy objects * then the exclusion strategies that were added will be applied as a disjunction rule. * This means that if one of the added exclusion strategies suggests that a field (or * class) should be skipped then that field (or object) is skipped during its * serialization. * * @param strategy an exclusion strategy to apply during serialization. * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern * @since 1.7 */ public GsonBuilder addSerializationExclusionStrategy(ExclusionStrategy strategy) { excluder = excluder.withExclusionStrategy(strategy, true, false); return this; } /** * Configures Gson to apply the passed in exclusion strategy during deserialization. * If this method is invoked numerous times with different exclusion strategy objects * then the exclusion strategies that were added will be applied as a disjunction rule. * This means that if one of the added exclusion strategies suggests that a field (or * class) should be skipped then that field (or object) is skipped during its * deserialization. * * @param strategy an exclusion strategy to apply during deserialization. * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern * @since 1.7 */ public GsonBuilder addDeserializationExclusionStrategy(ExclusionStrategy strategy) { excluder = excluder.withExclusionStrategy(strategy, false, true); return this; } /** * Configures Gson to output Json that fits in a page for pretty printing. This option only * affects Json serialization. * * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern */ public GsonBuilder setPrettyPrinting() { prettyPrinting = true; return this; } /** * By default, Gson is strict and only accepts JSON as specified by * RFC 4627. This option makes the parser * liberal in what it accepts. * * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern * @see JsonReader#setLenient(boolean) */ public GsonBuilder setLenient() { lenient = true; return this; } /** * By default, Gson escapes HTML characters such as < > etc. Use this option to configure * Gson to pass-through HTML characters as is. * * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern * @since 1.3 */ public GsonBuilder disableHtmlEscaping() { this.escapeHtmlChars = false; return this; } /** * Configures Gson to serialize {@code Date} objects according to the pattern provided. You can * call this method or {@link #setDateFormat(int)} multiple times, but only the last invocation * will be used to decide the serialization format. * *

The date format will be used to serialize and deserialize {@link java.util.Date}, {@link * java.sql.Timestamp} and {@link java.sql.Date}. * *

Note that this pattern must abide by the convention provided by {@code SimpleDateFormat} * class. See the documentation in {@link java.text.SimpleDateFormat} for more information on * valid date and time patterns.

* * @param pattern the pattern that dates will be serialized/deserialized to/from * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern * @since 1.2 */ public GsonBuilder setDateFormat(String pattern) { // TODO(Joel): Make this fail fast if it is an invalid date format this.datePattern = pattern; return this; } /** * Configures Gson to to serialize {@code Date} objects according to the style value provided. * You can call this method or {@link #setDateFormat(String)} multiple times, but only the last * invocation will be used to decide the serialization format. * *

Note that this style value should be one of the predefined constants in the * {@code DateFormat} class. See the documentation in {@link java.text.DateFormat} for more * information on the valid style constants.

* * @param style the predefined date style that date objects will be serialized/deserialized * to/from * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern * @since 1.2 */ public GsonBuilder setDateFormat(int style) { this.dateStyle = style; this.datePattern = null; return this; } /** * Configures Gson to to serialize {@code Date} objects according to the style value provided. * You can call this method or {@link #setDateFormat(String)} multiple times, but only the last * invocation will be used to decide the serialization format. * *

Note that this style value should be one of the predefined constants in the * {@code DateFormat} class. See the documentation in {@link java.text.DateFormat} for more * information on the valid style constants.

* * @param dateStyle the predefined date style that date objects will be serialized/deserialized * to/from * @param timeStyle the predefined style for the time portion of the date objects * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern * @since 1.2 */ public GsonBuilder setDateFormat(int dateStyle, int timeStyle) { this.dateStyle = dateStyle; this.timeStyle = timeStyle; this.datePattern = null; return this; } /** * Configures Gson for custom serialization or deserialization. This method combines the * registration of an {@link TypeAdapter}, {@link InstanceCreator}, {@link JsonSerializer}, and a * {@link JsonDeserializer}. It is best used when a single object {@code typeAdapter} implements * all the required interfaces for custom serialization with Gson. If a type adapter was * previously registered for the specified {@code type}, it is overwritten. * *

This registers the type specified and no other types: you must manually register related * types! For example, applications registering {@code boolean.class} should also register {@code * Boolean.class}. * * @param type the type definition for the type adapter being registered * @param typeAdapter This object must implement at least one of the {@link TypeAdapter}, * {@link InstanceCreator}, {@link JsonSerializer}, and a {@link JsonDeserializer} interfaces. * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern */ @SuppressWarnings({"unchecked", "rawtypes"}) public GsonBuilder registerTypeAdapter(Type type, Object typeAdapter) { $Gson$Preconditions.checkArgument(typeAdapter instanceof JsonSerializer || typeAdapter instanceof JsonDeserializer || typeAdapter instanceof InstanceCreator || typeAdapter instanceof TypeAdapter); if (typeAdapter instanceof InstanceCreator) { instanceCreators.put(type, (InstanceCreator) typeAdapter); } if (typeAdapter instanceof JsonSerializer || typeAdapter instanceof JsonDeserializer) { TypeToken typeToken = TypeToken.get(type); factories.add(TreeTypeAdapter.newFactoryWithMatchRawType(typeToken, typeAdapter)); } if (typeAdapter instanceof TypeAdapter) { factories.add(TypeAdapters.newFactory(TypeToken.get(type), (TypeAdapter)typeAdapter)); } return this; } /** * Register a factory for type adapters. Registering a factory is useful when the type * adapter needs to be configured based on the type of the field being processed. Gson * is designed to handle a large number of factories, so you should consider registering * them to be at par with registering an individual type adapter. * * @since 2.1 */ public GsonBuilder registerTypeAdapterFactory(TypeAdapterFactory factory) { factories.add(factory); return this; } /** * Configures Gson for custom serialization or deserialization for an inheritance type hierarchy. * This method combines the registration of a {@link TypeAdapter}, {@link JsonSerializer} and * a {@link JsonDeserializer}. If a type adapter was previously registered for the specified * type hierarchy, it is overridden. If a type adapter is registered for a specific type in * the type hierarchy, it will be invoked instead of the one registered for the type hierarchy. * * @param baseType the class definition for the type adapter being registered for the base class * or interface * @param typeAdapter This object must implement at least one of {@link TypeAdapter}, * {@link JsonSerializer} or {@link JsonDeserializer} interfaces. * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern * @since 1.7 */ @SuppressWarnings({"unchecked", "rawtypes"}) public GsonBuilder registerTypeHierarchyAdapter(Class baseType, Object typeAdapter) { $Gson$Preconditions.checkArgument(typeAdapter instanceof JsonSerializer || typeAdapter instanceof JsonDeserializer || typeAdapter instanceof TypeAdapter); if (typeAdapter instanceof JsonDeserializer || typeAdapter instanceof JsonSerializer) { hierarchyFactories.add(TreeTypeAdapter.newTypeHierarchyFactory(baseType, typeAdapter)); } if (typeAdapter instanceof TypeAdapter) { factories.add(TypeAdapters.newTypeHierarchyFactory(baseType, (TypeAdapter)typeAdapter)); } return this; } /** * Section 2.4 of JSON specification disallows * special double values (NaN, Infinity, -Infinity). However, * Javascript * specification (see section 4.3.20, 4.3.22, 4.3.23) allows these values as valid Javascript * values. Moreover, most JavaScript engines will accept these special values in JSON without * problem. So, at a practical level, it makes sense to accept these values as valid JSON even * though JSON specification disallows them. * *

Gson always accepts these special values during deserialization. However, it outputs * strictly compliant JSON. Hence, if it encounters a float value {@link Float#NaN}, * {@link Float#POSITIVE_INFINITY}, {@link Float#NEGATIVE_INFINITY}, or a double value * {@link Double#NaN}, {@link Double#POSITIVE_INFINITY}, {@link Double#NEGATIVE_INFINITY}, it * will throw an {@link IllegalArgumentException}. This method provides a way to override the * default behavior when you know that the JSON receiver will be able to handle these special * values. * * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern * @since 1.3 */ public GsonBuilder serializeSpecialFloatingPointValues() { this.serializeSpecialFloatingPointValues = true; return this; } /** * Creates a {@link Gson} instance based on the current configuration. This method is free of * side-effects to this {@code GsonBuilder} instance and hence can be called multiple times. * * @return an instance of Gson configured with the options currently set in this builder */ public Gson create() { List factories = new ArrayList(this.factories.size() + this.hierarchyFactories.size() + 3); factories.addAll(this.factories); Collections.reverse(factories); List hierarchyFactories = new ArrayList(this.hierarchyFactories); Collections.reverse(hierarchyFactories); factories.addAll(hierarchyFactories); addTypeAdaptersForDate(datePattern, dateStyle, timeStyle, factories); return new Gson(excluder, fieldNamingPolicy, instanceCreators, serializeNulls, complexMapKeySerialization, generateNonExecutableJson, escapeHtmlChars, prettyPrinting, lenient, serializeSpecialFloatingPointValues, longSerializationPolicy, factories); } @SuppressWarnings("unchecked") private void addTypeAdaptersForDate(String datePattern, int dateStyle, int timeStyle, List factories) { DefaultDateTypeAdapter dateTypeAdapter; TypeAdapter timestampTypeAdapter; TypeAdapter javaSqlDateTypeAdapter; if (datePattern != null && !"".equals(datePattern.trim())) { dateTypeAdapter = new DefaultDateTypeAdapter(Date.class, datePattern); timestampTypeAdapter = (TypeAdapter) new DefaultDateTypeAdapter(Timestamp.class, datePattern); javaSqlDateTypeAdapter = (TypeAdapter) new DefaultDateTypeAdapter(java.sql.Date.class, datePattern); } else if (dateStyle != DateFormat.DEFAULT && timeStyle != DateFormat.DEFAULT) { dateTypeAdapter = new DefaultDateTypeAdapter(Date.class, dateStyle, timeStyle); timestampTypeAdapter = (TypeAdapter) new DefaultDateTypeAdapter(Timestamp.class, dateStyle, timeStyle); javaSqlDateTypeAdapter = (TypeAdapter) new DefaultDateTypeAdapter(java.sql.Date.class, dateStyle, timeStyle); } else { return; } factories.add(TypeAdapters.newFactory(Date.class, dateTypeAdapter)); factories.add(TypeAdapters.newFactory(Timestamp.class, timestampTypeAdapter)); factories.add(TypeAdapters.newFactory(java.sql.Date.class, javaSqlDateTypeAdapter)); } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/InstanceCreator.java000066400000000000000000000071571316034351600272710ustar00rootroot00000000000000/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson; import java.lang.reflect.Type; /** * This interface is implemented to create instances of a class that does not define a no-args * constructor. If you can modify the class, you should instead add a private, or public * no-args constructor. However, that is not possible for library classes, such as JDK classes, or * a third-party library that you do not have source-code of. In such cases, you should define an * instance creator for the class. Implementations of this interface should be registered with * {@link GsonBuilder#registerTypeAdapter(Type, Object)} method before Gson will be able to use * them. *

Let us look at an example where defining an InstanceCreator might be useful. The * {@code Id} class defined below does not have a default no-args constructor.

* *
 * public class Id<T> {
 *   private final Class<T> clazz;
 *   private final long value;
 *   public Id(Class<T> clazz, long value) {
 *     this.clazz = clazz;
 *     this.value = value;
 *   }
 * }
 * 
* *

If Gson encounters an object of type {@code Id} during deserialization, it will throw an * exception. The easiest way to solve this problem will be to add a (public or private) no-args * constructor as follows:

* *
 * private Id() {
 *   this(Object.class, 0L);
 * }
 * 
* *

However, let us assume that the developer does not have access to the source-code of the * {@code Id} class, or does not want to define a no-args constructor for it. The developer * can solve this problem by defining an {@code InstanceCreator} for {@code Id}:

* *
 * class IdInstanceCreator implements InstanceCreator<Id> {
 *   public Id createInstance(Type type) {
 *     return new Id(Object.class, 0L);
 *   }
 * }
 * 
* *

Note that it does not matter what the fields of the created instance contain since Gson will * overwrite them with the deserialized values specified in Json. You should also ensure that a * new object is returned, not a common object since its fields will be overwritten. * The developer will need to register {@code IdInstanceCreator} with Gson as follows:

* *
 * Gson gson = new GsonBuilder().registerTypeAdapter(Id.class, new IdInstanceCreator()).create();
 * 
* * @param the type of object that will be created by this implementation. * * @author Inderjeet Singh * @author Joel Leitch */ public interface InstanceCreator { /** * Gson invokes this call-back method during deserialization to create an instance of the * specified type. The fields of the returned instance are overwritten with the data present * in the Json. Since the prior contents of the object are destroyed and overwritten, do not * return an instance that is useful elsewhere. In particular, do not return a common instance, * always use {@code new} to create a new instance. * * @param type the parameterized T represented as a {@link Type}. * @return a default object instance of type T. */ public T createInstance(Type type); } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/JsonArray.java000066400000000000000000000276621316034351600261200ustar00rootroot00000000000000/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * A class representing an array type in Json. An array is a list of {@link JsonElement}s each of * which can be of a different type. This is an ordered list, meaning that the order in which * elements are added is preserved. * * @author Inderjeet Singh * @author Joel Leitch */ public final class JsonArray extends JsonElement implements Iterable { private final List elements; /** * Creates an empty JsonArray. */ public JsonArray() { elements = new ArrayList(); } public JsonArray(int capacity) { elements = new ArrayList(capacity); } /** * Creates a deep copy of this element and all its children * @since 2.8.2 */ @Override public JsonArray deepCopy() { if (!elements.isEmpty()) { JsonArray result = new JsonArray(elements.size()); for (JsonElement element : elements) { result.add(element.deepCopy()); } return result; } return new JsonArray(); } /** * Adds the specified boolean to self. * * @param bool the boolean that needs to be added to the array. */ public void add(Boolean bool) { elements.add(bool == null ? JsonNull.INSTANCE : new JsonPrimitive(bool)); } /** * Adds the specified character to self. * * @param character the character that needs to be added to the array. */ public void add(Character character) { elements.add(character == null ? JsonNull.INSTANCE : new JsonPrimitive(character)); } /** * Adds the specified number to self. * * @param number the number that needs to be added to the array. */ public void add(Number number) { elements.add(number == null ? JsonNull.INSTANCE : new JsonPrimitive(number)); } /** * Adds the specified string to self. * * @param string the string that needs to be added to the array. */ public void add(String string) { elements.add(string == null ? JsonNull.INSTANCE : new JsonPrimitive(string)); } /** * Adds the specified element to self. * * @param element the element that needs to be added to the array. */ public void add(JsonElement element) { if (element == null) { element = JsonNull.INSTANCE; } elements.add(element); } /** * Adds all the elements of the specified array to self. * * @param array the array whose elements need to be added to the array. */ public void addAll(JsonArray array) { elements.addAll(array.elements); } /** * Replaces the element at the specified position in this array with the specified element. * Element can be null. * @param index index of the element to replace * @param element element to be stored at the specified position * @return the element previously at the specified position * @throws IndexOutOfBoundsException if the specified index is outside the array bounds */ public JsonElement set(int index, JsonElement element) { return elements.set(index, element); } /** * Removes the first occurrence of the specified element from this array, if it is present. * If the array does not contain the element, it is unchanged. * @param element element to be removed from this array, if present * @return true if this array contained the specified element, false otherwise * @since 2.3 */ public boolean remove(JsonElement element) { return elements.remove(element); } /** * Removes the element at the specified position in this array. Shifts any subsequent elements * to the left (subtracts one from their indices). Returns the element that was removed from * the array. * @param index index the index of the element to be removed * @return the element previously at the specified position * @throws IndexOutOfBoundsException if the specified index is outside the array bounds * @since 2.3 */ public JsonElement remove(int index) { return elements.remove(index); } /** * Returns true if this array contains the specified element. * @return true if this array contains the specified element. * @param element whose presence in this array is to be tested * @since 2.3 */ public boolean contains(JsonElement element) { return elements.contains(element); } /** * Returns the number of elements in the array. * * @return the number of elements in the array. */ public int size() { return elements.size(); } /** * Returns an iterator to navigate the elements of the array. Since the array is an ordered list, * the iterator navigates the elements in the order they were inserted. * * @return an iterator to navigate the elements of the array. */ public Iterator iterator() { return elements.iterator(); } /** * Returns the ith element of the array. * * @param i the index of the element that is being sought. * @return the element present at the ith index. * @throws IndexOutOfBoundsException if i is negative or greater than or equal to the * {@link #size()} of the array. */ public JsonElement get(int i) { return elements.get(i); } /** * convenience method to get this array as a {@link Number} if it contains a single element. * * @return get this element as a number if it is single element array. * @throws ClassCastException if the element in the array is of not a {@link JsonPrimitive} and * is not a valid Number. * @throws IllegalStateException if the array has more than one element. */ @Override public Number getAsNumber() { if (elements.size() == 1) { return elements.get(0).getAsNumber(); } throw new IllegalStateException(); } /** * convenience method to get this array as a {@link String} if it contains a single element. * * @return get this element as a String if it is single element array. * @throws ClassCastException if the element in the array is of not a {@link JsonPrimitive} and * is not a valid String. * @throws IllegalStateException if the array has more than one element. */ @Override public String getAsString() { if (elements.size() == 1) { return elements.get(0).getAsString(); } throw new IllegalStateException(); } /** * convenience method to get this array as a double if it contains a single element. * * @return get this element as a double if it is single element array. * @throws ClassCastException if the element in the array is of not a {@link JsonPrimitive} and * is not a valid double. * @throws IllegalStateException if the array has more than one element. */ @Override public double getAsDouble() { if (elements.size() == 1) { return elements.get(0).getAsDouble(); } throw new IllegalStateException(); } /** * convenience method to get this array as a {@link BigDecimal} if it contains a single element. * * @return get this element as a {@link BigDecimal} if it is single element array. * @throws ClassCastException if the element in the array is of not a {@link JsonPrimitive}. * @throws NumberFormatException if the element at index 0 is not a valid {@link BigDecimal}. * @throws IllegalStateException if the array has more than one element. * @since 1.2 */ @Override public BigDecimal getAsBigDecimal() { if (elements.size() == 1) { return elements.get(0).getAsBigDecimal(); } throw new IllegalStateException(); } /** * convenience method to get this array as a {@link BigInteger} if it contains a single element. * * @return get this element as a {@link BigInteger} if it is single element array. * @throws ClassCastException if the element in the array is of not a {@link JsonPrimitive}. * @throws NumberFormatException if the element at index 0 is not a valid {@link BigInteger}. * @throws IllegalStateException if the array has more than one element. * @since 1.2 */ @Override public BigInteger getAsBigInteger() { if (elements.size() == 1) { return elements.get(0).getAsBigInteger(); } throw new IllegalStateException(); } /** * convenience method to get this array as a float if it contains a single element. * * @return get this element as a float if it is single element array. * @throws ClassCastException if the element in the array is of not a {@link JsonPrimitive} and * is not a valid float. * @throws IllegalStateException if the array has more than one element. */ @Override public float getAsFloat() { if (elements.size() == 1) { return elements.get(0).getAsFloat(); } throw new IllegalStateException(); } /** * convenience method to get this array as a long if it contains a single element. * * @return get this element as a long if it is single element array. * @throws ClassCastException if the element in the array is of not a {@link JsonPrimitive} and * is not a valid long. * @throws IllegalStateException if the array has more than one element. */ @Override public long getAsLong() { if (elements.size() == 1) { return elements.get(0).getAsLong(); } throw new IllegalStateException(); } /** * convenience method to get this array as an integer if it contains a single element. * * @return get this element as an integer if it is single element array. * @throws ClassCastException if the element in the array is of not a {@link JsonPrimitive} and * is not a valid integer. * @throws IllegalStateException if the array has more than one element. */ @Override public int getAsInt() { if (elements.size() == 1) { return elements.get(0).getAsInt(); } throw new IllegalStateException(); } @Override public byte getAsByte() { if (elements.size() == 1) { return elements.get(0).getAsByte(); } throw new IllegalStateException(); } @Override public char getAsCharacter() { if (elements.size() == 1) { return elements.get(0).getAsCharacter(); } throw new IllegalStateException(); } /** * convenience method to get this array as a primitive short if it contains a single element. * * @return get this element as a primitive short if it is single element array. * @throws ClassCastException if the element in the array is of not a {@link JsonPrimitive} and * is not a valid short. * @throws IllegalStateException if the array has more than one element. */ @Override public short getAsShort() { if (elements.size() == 1) { return elements.get(0).getAsShort(); } throw new IllegalStateException(); } /** * convenience method to get this array as a boolean if it contains a single element. * * @return get this element as a boolean if it is single element array. * @throws ClassCastException if the element in the array is of not a {@link JsonPrimitive} and * is not a valid boolean. * @throws IllegalStateException if the array has more than one element. */ @Override public boolean getAsBoolean() { if (elements.size() == 1) { return elements.get(0).getAsBoolean(); } throw new IllegalStateException(); } @Override public boolean equals(Object o) { return (o == this) || (o instanceof JsonArray && ((JsonArray) o).elements.equals(elements)); } @Override public int hashCode() { return elements.hashCode(); } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/JsonDeserializationContext.java000066400000000000000000000032021316034351600315150ustar00rootroot00000000000000/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson; import java.lang.reflect.Type; /** * Context for deserialization that is passed to a custom deserializer during invocation of its * {@link JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext)} * method. * * @author Inderjeet Singh * @author Joel Leitch */ public interface JsonDeserializationContext { /** * Invokes default deserialization on the specified object. It should never be invoked on * the element received as a parameter of the * {@link JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext)} method. Doing * so will result in an infinite loop since Gson will in-turn call the custom deserializer again. * * @param json the parse tree. * @param typeOfT type of the expected return value. * @param The type of the deserialized object. * @return An object of type typeOfT. * @throws JsonParseException if the parse tree does not contain expected data. */ public T deserialize(JsonElement json, Type typeOfT) throws JsonParseException; }gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/JsonDeserializer.java000066400000000000000000000071351316034351600274550ustar00rootroot00000000000000/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson; import java.lang.reflect.Type; /** *

Interface representing a custom deserializer for Json. You should write a custom * deserializer, if you are not happy with the default deserialization done by Gson. You will * also need to register this deserializer through * {@link GsonBuilder#registerTypeAdapter(Type, Object)}.

* *

Let us look at example where defining a deserializer will be useful. The {@code Id} class * defined below has two fields: {@code clazz} and {@code value}.

* *
 * public class Id<T> {
 *   private final Class<T> clazz;
 *   private final long value;
 *   public Id(Class<T> clazz, long value) {
 *     this.clazz = clazz;
 *     this.value = value;
 *   }
 *   public long getValue() {
 *     return value;
 *   }
 * }
 * 
* *

The default deserialization of {@code Id(com.foo.MyObject.class, 20L)} will require the * Json string to be {"clazz":com.foo.MyObject,"value":20}. Suppose, you already know * the type of the field that the {@code Id} will be deserialized into, and hence just want to * deserialize it from a Json string {@code 20}. You can achieve that by writing a custom * deserializer:

* *
 * class IdDeserializer implements JsonDeserializer<Id>() {
 *   public Id deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
 *       throws JsonParseException {
 *     return new Id((Class)typeOfT, id.getValue());
 *   }
 * 
* *

You will also need to register {@code IdDeserializer} with Gson as follows:

* *
 * Gson gson = new GsonBuilder().registerTypeAdapter(Id.class, new IdDeserializer()).create();
 * 
* *

New applications should prefer {@link TypeAdapter}, whose streaming API * is more efficient than this interface's tree API. * * @author Inderjeet Singh * @author Joel Leitch * * @param type for which the deserializer is being registered. It is possible that a * deserializer may be asked to deserialize a specific generic type of the T. */ public interface JsonDeserializer { /** * Gson invokes this call-back method during deserialization when it encounters a field of the * specified type. *

In the implementation of this call-back method, you should consider invoking * {@link JsonDeserializationContext#deserialize(JsonElement, Type)} method to create objects * for any non-trivial field of the returned object. However, you should never invoke it on the * the same type passing {@code json} since that will cause an infinite loop (Gson will call your * call-back method again). * * @param json The Json data being deserialized * @param typeOfT The type of the Object to deserialize to * @return a deserialized object of the specified type typeOfT which is a subclass of {@code T} * @throws JsonParseException if json is not in the expected format of {@code typeofT} */ public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException; } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/JsonElement.java000066400000000000000000000271311316034351600264220ustar00rootroot00000000000000/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson; import com.google.gson.internal.Streams; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.io.StringWriter; import java.math.BigDecimal; import java.math.BigInteger; /** * A class representing an element of Json. It could either be a {@link JsonObject}, a * {@link JsonArray}, a {@link JsonPrimitive} or a {@link JsonNull}. * * @author Inderjeet Singh * @author Joel Leitch */ public abstract class JsonElement { /** * Returns a deep copy of this element. Immutable elements like primitives * and nulls are not copied. * @since 2.8.2 */ public abstract JsonElement deepCopy(); /** * provides check for verifying if this element is an array or not. * * @return true if this element is of type {@link JsonArray}, false otherwise. */ public boolean isJsonArray() { return this instanceof JsonArray; } /** * provides check for verifying if this element is a Json object or not. * * @return true if this element is of type {@link JsonObject}, false otherwise. */ public boolean isJsonObject() { return this instanceof JsonObject; } /** * provides check for verifying if this element is a primitive or not. * * @return true if this element is of type {@link JsonPrimitive}, false otherwise. */ public boolean isJsonPrimitive() { return this instanceof JsonPrimitive; } /** * provides check for verifying if this element represents a null value or not. * * @return true if this element is of type {@link JsonNull}, false otherwise. * @since 1.2 */ public boolean isJsonNull() { return this instanceof JsonNull; } /** * convenience method to get this element as a {@link JsonObject}. If the element is of some * other type, a {@link IllegalStateException} will result. Hence it is best to use this method * after ensuring that this element is of the desired type by calling {@link #isJsonObject()} * first. * * @return get this element as a {@link JsonObject}. * @throws IllegalStateException if the element is of another type. */ public JsonObject getAsJsonObject() { if (isJsonObject()) { return (JsonObject) this; } throw new IllegalStateException("Not a JSON Object: " + this); } /** * convenience method to get this element as a {@link JsonArray}. If the element is of some * other type, a {@link IllegalStateException} will result. Hence it is best to use this method * after ensuring that this element is of the desired type by calling {@link #isJsonArray()} * first. * * @return get this element as a {@link JsonArray}. * @throws IllegalStateException if the element is of another type. */ public JsonArray getAsJsonArray() { if (isJsonArray()) { return (JsonArray) this; } throw new IllegalStateException("Not a JSON Array: " + this); } /** * convenience method to get this element as a {@link JsonPrimitive}. If the element is of some * other type, a {@link IllegalStateException} will result. Hence it is best to use this method * after ensuring that this element is of the desired type by calling {@link #isJsonPrimitive()} * first. * * @return get this element as a {@link JsonPrimitive}. * @throws IllegalStateException if the element is of another type. */ public JsonPrimitive getAsJsonPrimitive() { if (isJsonPrimitive()) { return (JsonPrimitive) this; } throw new IllegalStateException("Not a JSON Primitive: " + this); } /** * convenience method to get this element as a {@link JsonNull}. If the element is of some * other type, a {@link IllegalStateException} will result. Hence it is best to use this method * after ensuring that this element is of the desired type by calling {@link #isJsonNull()} * first. * * @return get this element as a {@link JsonNull}. * @throws IllegalStateException if the element is of another type. * @since 1.2 */ public JsonNull getAsJsonNull() { if (isJsonNull()) { return (JsonNull) this; } throw new IllegalStateException("Not a JSON Null: " + this); } /** * convenience method to get this element as a boolean value. * * @return get this element as a primitive boolean value. * @throws ClassCastException if the element is of not a {@link JsonPrimitive} and is not a valid * boolean value. * @throws IllegalStateException if the element is of the type {@link JsonArray} but contains * more than a single element. */ public boolean getAsBoolean() { throw new UnsupportedOperationException(getClass().getSimpleName()); } /** * convenience method to get this element as a {@link Boolean} value. * * @return get this element as a {@link Boolean} value. * @throws ClassCastException if the element is of not a {@link JsonPrimitive} and is not a valid * boolean value. * @throws IllegalStateException if the element is of the type {@link JsonArray} but contains * more than a single element. */ Boolean getAsBooleanWrapper() { throw new UnsupportedOperationException(getClass().getSimpleName()); } /** * convenience method to get this element as a {@link Number}. * * @return get this element as a {@link Number}. * @throws ClassCastException if the element is of not a {@link JsonPrimitive} and is not a valid * number. * @throws IllegalStateException if the element is of the type {@link JsonArray} but contains * more than a single element. */ public Number getAsNumber() { throw new UnsupportedOperationException(getClass().getSimpleName()); } /** * convenience method to get this element as a string value. * * @return get this element as a string value. * @throws ClassCastException if the element is of not a {@link JsonPrimitive} and is not a valid * string value. * @throws IllegalStateException if the element is of the type {@link JsonArray} but contains * more than a single element. */ public String getAsString() { throw new UnsupportedOperationException(getClass().getSimpleName()); } /** * convenience method to get this element as a primitive double value. * * @return get this element as a primitive double value. * @throws ClassCastException if the element is of not a {@link JsonPrimitive} and is not a valid * double value. * @throws IllegalStateException if the element is of the type {@link JsonArray} but contains * more than a single element. */ public double getAsDouble() { throw new UnsupportedOperationException(getClass().getSimpleName()); } /** * convenience method to get this element as a primitive float value. * * @return get this element as a primitive float value. * @throws ClassCastException if the element is of not a {@link JsonPrimitive} and is not a valid * float value. * @throws IllegalStateException if the element is of the type {@link JsonArray} but contains * more than a single element. */ public float getAsFloat() { throw new UnsupportedOperationException(getClass().getSimpleName()); } /** * convenience method to get this element as a primitive long value. * * @return get this element as a primitive long value. * @throws ClassCastException if the element is of not a {@link JsonPrimitive} and is not a valid * long value. * @throws IllegalStateException if the element is of the type {@link JsonArray} but contains * more than a single element. */ public long getAsLong() { throw new UnsupportedOperationException(getClass().getSimpleName()); } /** * convenience method to get this element as a primitive integer value. * * @return get this element as a primitive integer value. * @throws ClassCastException if the element is of not a {@link JsonPrimitive} and is not a valid * integer value. * @throws IllegalStateException if the element is of the type {@link JsonArray} but contains * more than a single element. */ public int getAsInt() { throw new UnsupportedOperationException(getClass().getSimpleName()); } /** * convenience method to get this element as a primitive byte value. * * @return get this element as a primitive byte value. * @throws ClassCastException if the element is of not a {@link JsonPrimitive} and is not a valid * byte value. * @throws IllegalStateException if the element is of the type {@link JsonArray} but contains * more than a single element. * @since 1.3 */ public byte getAsByte() { throw new UnsupportedOperationException(getClass().getSimpleName()); } /** * convenience method to get this element as a primitive character value. * * @return get this element as a primitive char value. * @throws ClassCastException if the element is of not a {@link JsonPrimitive} and is not a valid * char value. * @throws IllegalStateException if the element is of the type {@link JsonArray} but contains * more than a single element. * @since 1.3 */ public char getAsCharacter() { throw new UnsupportedOperationException(getClass().getSimpleName()); } /** * convenience method to get this element as a {@link BigDecimal}. * * @return get this element as a {@link BigDecimal}. * @throws ClassCastException if the element is of not a {@link JsonPrimitive}. * * @throws NumberFormatException if the element is not a valid {@link BigDecimal}. * @throws IllegalStateException if the element is of the type {@link JsonArray} but contains * more than a single element. * @since 1.2 */ public BigDecimal getAsBigDecimal() { throw new UnsupportedOperationException(getClass().getSimpleName()); } /** * convenience method to get this element as a {@link BigInteger}. * * @return get this element as a {@link BigInteger}. * @throws ClassCastException if the element is of not a {@link JsonPrimitive}. * @throws NumberFormatException if the element is not a valid {@link BigInteger}. * @throws IllegalStateException if the element is of the type {@link JsonArray} but contains * more than a single element. * @since 1.2 */ public BigInteger getAsBigInteger() { throw new UnsupportedOperationException(getClass().getSimpleName()); } /** * convenience method to get this element as a primitive short value. * * @return get this element as a primitive short value. * @throws ClassCastException if the element is of not a {@link JsonPrimitive} and is not a valid * short value. * @throws IllegalStateException if the element is of the type {@link JsonArray} but contains * more than a single element. */ public short getAsShort() { throw new UnsupportedOperationException(getClass().getSimpleName()); } /** * Returns a String representation of this element. */ @Override public String toString() { try { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.setLenient(true); Streams.write(this, jsonWriter); return stringWriter.toString(); } catch (IOException e) { throw new AssertionError(e); } } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/JsonIOException.java000066400000000000000000000025071316034351600272170ustar00rootroot00000000000000/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson; /** * This exception is raised when Gson was unable to read an input stream * or write to one. * * @author Inderjeet Singh * @author Joel Leitch */ public final class JsonIOException extends JsonParseException { private static final long serialVersionUID = 1L; public JsonIOException(String msg) { super(msg); } public JsonIOException(String msg, Throwable cause) { super(msg, cause); } /** * Creates exception with the specified cause. Consider using * {@link #JsonIOException(String, Throwable)} instead if you can describe what happened. * * @param cause root exception that caused this exception to be thrown. */ public JsonIOException(Throwable cause) { super(cause); } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/JsonNull.java000077500000000000000000000032111316034351600257370ustar00rootroot00000000000000/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson; /** * A class representing a Json {@code null} value. * * @author Inderjeet Singh * @author Joel Leitch * @since 1.2 */ public final class JsonNull extends JsonElement { /** * singleton for JsonNull * * @since 1.8 */ public static final JsonNull INSTANCE = new JsonNull(); /** * Creates a new JsonNull object. * Deprecated since Gson version 1.8. Use {@link #INSTANCE} instead */ @Deprecated public JsonNull() { // Do nothing } /** * Returns the same instance since it is an immutable value * @since 2.8.2 */ @Override public JsonNull deepCopy() { return INSTANCE; } /** * All instances of JsonNull have the same hash code since they are indistinguishable */ @Override public int hashCode() { return JsonNull.class.hashCode(); } /** * All instances of JsonNull are the same */ @Override public boolean equals(Object other) { return this == other || other instanceof JsonNull; } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/JsonObject.java000066400000000000000000000150621316034351600262370ustar00rootroot00000000000000/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson; import com.google.gson.internal.LinkedTreeMap; import java.util.Map; import java.util.Set; /** * A class representing an object type in Json. An object consists of name-value pairs where names * are strings, and values are any other type of {@link JsonElement}. This allows for a creating a * tree of JsonElements. The member elements of this object are maintained in order they were added. * * @author Inderjeet Singh * @author Joel Leitch */ public final class JsonObject extends JsonElement { private final LinkedTreeMap members = new LinkedTreeMap(); /** * Creates a deep copy of this element and all its children * @since 2.8.2 */ @Override public JsonObject deepCopy() { JsonObject result = new JsonObject(); for (Map.Entry entry : members.entrySet()) { result.add(entry.getKey(), entry.getValue().deepCopy()); } return result; } /** * Adds a member, which is a name-value pair, to self. The name must be a String, but the value * can be an arbitrary JsonElement, thereby allowing you to build a full tree of JsonElements * rooted at this node. * * @param property name of the member. * @param value the member object. */ public void add(String property, JsonElement value) { if (value == null) { value = JsonNull.INSTANCE; } members.put(property, value); } /** * Removes the {@code property} from this {@link JsonObject}. * * @param property name of the member that should be removed. * @return the {@link JsonElement} object that is being removed. * @since 1.3 */ public JsonElement remove(String property) { return members.remove(property); } /** * Convenience method to add a primitive member. The specified value is converted to a * JsonPrimitive of String. * * @param property name of the member. * @param value the string value associated with the member. */ public void addProperty(String property, String value) { add(property, createJsonElement(value)); } /** * Convenience method to add a primitive member. The specified value is converted to a * JsonPrimitive of Number. * * @param property name of the member. * @param value the number value associated with the member. */ public void addProperty(String property, Number value) { add(property, createJsonElement(value)); } /** * Convenience method to add a boolean member. The specified value is converted to a * JsonPrimitive of Boolean. * * @param property name of the member. * @param value the number value associated with the member. */ public void addProperty(String property, Boolean value) { add(property, createJsonElement(value)); } /** * Convenience method to add a char member. The specified value is converted to a * JsonPrimitive of Character. * * @param property name of the member. * @param value the number value associated with the member. */ public void addProperty(String property, Character value) { add(property, createJsonElement(value)); } /** * Creates the proper {@link JsonElement} object from the given {@code value} object. * * @param value the object to generate the {@link JsonElement} for * @return a {@link JsonPrimitive} if the {@code value} is not null, otherwise a {@link JsonNull} */ private JsonElement createJsonElement(Object value) { return value == null ? JsonNull.INSTANCE : new JsonPrimitive(value); } /** * Returns a set of members of this object. The set is ordered, and the order is in which the * elements were added. * * @return a set of members of this object. */ public Set> entrySet() { return members.entrySet(); } /** * Returns a set of members key values. * * @return a set of member keys as Strings * @since 2.8.1 */ public Set keySet() { return members.keySet(); } /** * Returns the number of key/value pairs in the object. * * @return the number of key/value pairs in the object. */ public int size() { return members.size(); } /** * Convenience method to check if a member with the specified name is present in this object. * * @param memberName name of the member that is being checked for presence. * @return true if there is a member with the specified name, false otherwise. */ public boolean has(String memberName) { return members.containsKey(memberName); } /** * Returns the member with the specified name. * * @param memberName name of the member that is being requested. * @return the member matching the name. Null if no such member exists. */ public JsonElement get(String memberName) { return members.get(memberName); } /** * Convenience method to get the specified member as a JsonPrimitive element. * * @param memberName name of the member being requested. * @return the JsonPrimitive corresponding to the specified member. */ public JsonPrimitive getAsJsonPrimitive(String memberName) { return (JsonPrimitive) members.get(memberName); } /** * Convenience method to get the specified member as a JsonArray. * * @param memberName name of the member being requested. * @return the JsonArray corresponding to the specified member. */ public JsonArray getAsJsonArray(String memberName) { return (JsonArray) members.get(memberName); } /** * Convenience method to get the specified member as a JsonObject. * * @param memberName name of the member being requested. * @return the JsonObject corresponding to the specified member. */ public JsonObject getAsJsonObject(String memberName) { return (JsonObject) members.get(memberName); } @Override public boolean equals(Object o) { return (o == this) || (o instanceof JsonObject && ((JsonObject) o).members.equals(members)); } @Override public int hashCode() { return members.hashCode(); } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/JsonParseException.java000066400000000000000000000045301316034351600277600ustar00rootroot00000000000000/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson; /** * This exception is raised if there is a serious issue that occurs during parsing of a Json * string. One of the main usages for this class is for the Gson infrastructure. If the incoming * Json is bad/malicious, an instance of this exception is raised. * *

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

* * @author Inderjeet Singh * @author Joel Leitch */ public class JsonParseException extends RuntimeException { static final long serialVersionUID = -4086729973971783390L; /** * Creates exception with the specified message. If you are wrapping another exception, consider * using {@link #JsonParseException(String, Throwable)} instead. * * @param msg error message describing a possible cause of this exception. */ public JsonParseException(String msg) { super(msg); } /** * Creates exception with the specified message and cause. * * @param msg error message describing what happened. * @param cause root exception that caused this exception to be thrown. */ public JsonParseException(String msg, Throwable cause) { super(msg, cause); } /** * Creates exception with the specified cause. Consider using * {@link #JsonParseException(String, Throwable)} instead if you can describe what happened. * * @param cause root exception that caused this exception to be thrown. */ public JsonParseException(Throwable cause) { super(cause); } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/JsonParser.java000077500000000000000000000061331316034351600262670ustar00rootroot00000000000000/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import com.google.gson.internal.Streams; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.MalformedJsonException; /** * A parser to parse Json into a parse tree of {@link JsonElement}s * * @author Inderjeet Singh * @author Joel Leitch * @since 1.3 */ public final class JsonParser { /** * Parses the specified JSON string into a parse tree * * @param json JSON text * @return a parse tree of {@link JsonElement}s corresponding to the specified JSON * @throws JsonParseException if the specified text is not valid JSON * @since 1.3 */ public JsonElement parse(String json) throws JsonSyntaxException { return parse(new StringReader(json)); } /** * Parses the specified JSON string into a parse tree * * @param json JSON text * @return a parse tree of {@link JsonElement}s corresponding to the specified JSON * @throws JsonParseException if the specified text is not valid JSON * @since 1.3 */ public JsonElement parse(Reader json) throws JsonIOException, JsonSyntaxException { try { JsonReader jsonReader = new JsonReader(json); JsonElement element = parse(jsonReader); if (!element.isJsonNull() && jsonReader.peek() != JsonToken.END_DOCUMENT) { throw new JsonSyntaxException("Did not consume the entire document."); } return element; } catch (MalformedJsonException e) { throw new JsonSyntaxException(e); } catch (IOException e) { throw new JsonIOException(e); } catch (NumberFormatException e) { throw new JsonSyntaxException(e); } } /** * Returns the next value from the JSON stream as a parse tree. * * @throws JsonParseException if there is an IOException or if the specified * text is not valid JSON * @since 1.6 */ public JsonElement parse(JsonReader json) throws JsonIOException, JsonSyntaxException { boolean lenient = json.isLenient(); json.setLenient(true); try { return Streams.parse(json); } catch (StackOverflowError e) { throw new JsonParseException("Failed parsing JSON source: " + json + " to Json", e); } catch (OutOfMemoryError e) { throw new JsonParseException("Failed parsing JSON source: " + json + " to Json", e); } finally { json.setLenient(lenient); } } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/JsonPrimitive.java000066400000000000000000000233021316034351600267750ustar00rootroot00000000000000/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson; import java.math.BigDecimal; import java.math.BigInteger; import com.google.gson.internal.$Gson$Preconditions; import com.google.gson.internal.LazilyParsedNumber; /** * A class representing a Json primitive value. A primitive value * is either a String, a Java primitive, or a Java primitive * wrapper type. * * @author Inderjeet Singh * @author Joel Leitch */ public final class JsonPrimitive extends JsonElement { private static final Class[] PRIMITIVE_TYPES = { int.class, long.class, short.class, float.class, double.class, byte.class, boolean.class, char.class, Integer.class, Long.class, Short.class, Float.class, Double.class, Byte.class, Boolean.class, Character.class }; private Object value; /** * Create a primitive containing a boolean value. * * @param bool the value to create the primitive with. */ public JsonPrimitive(Boolean bool) { setValue(bool); } /** * Create a primitive containing a {@link Number}. * * @param number the value to create the primitive with. */ public JsonPrimitive(Number number) { setValue(number); } /** * Create a primitive containing a String value. * * @param string the value to create the primitive with. */ public JsonPrimitive(String string) { setValue(string); } /** * Create a primitive containing a character. The character is turned into a one character String * since Json only supports String. * * @param c the value to create the primitive with. */ public JsonPrimitive(Character c) { setValue(c); } /** * Create a primitive using the specified Object. It must be an instance of {@link Number}, a * Java primitive type, or a String. * * @param primitive the value to create the primitive with. */ JsonPrimitive(Object primitive) { setValue(primitive); } /** * Returns the same value as primitives are immutable. * @since 2.8.2 */ @Override public JsonPrimitive deepCopy() { return this; } void setValue(Object primitive) { if (primitive instanceof Character) { // convert characters to strings since in JSON, characters are represented as a single // character string char c = ((Character) primitive).charValue(); this.value = String.valueOf(c); } else { $Gson$Preconditions.checkArgument(primitive instanceof Number || isPrimitiveOrString(primitive)); this.value = primitive; } } /** * Check whether this primitive contains a boolean value. * * @return true if this primitive contains a boolean value, false otherwise. */ public boolean isBoolean() { return value instanceof Boolean; } /** * convenience method to get this element as a {@link Boolean}. * * @return get this element as a {@link Boolean}. */ @Override Boolean getAsBooleanWrapper() { return (Boolean) value; } /** * convenience method to get this element as a boolean value. * * @return get this element as a primitive boolean value. */ @Override public boolean getAsBoolean() { if (isBoolean()) { return getAsBooleanWrapper().booleanValue(); } else { // Check to see if the value as a String is "true" in any case. return Boolean.parseBoolean(getAsString()); } } /** * Check whether this primitive contains a Number. * * @return true if this primitive contains a Number, false otherwise. */ public boolean isNumber() { return value instanceof Number; } /** * convenience method to get this element as a Number. * * @return get this element as a Number. * @throws NumberFormatException if the value contained is not a valid Number. */ @Override public Number getAsNumber() { return value instanceof String ? new LazilyParsedNumber((String) value) : (Number) value; } /** * Check whether this primitive contains a String value. * * @return true if this primitive contains a String value, false otherwise. */ public boolean isString() { return value instanceof String; } /** * convenience method to get this element as a String. * * @return get this element as a String. */ @Override public String getAsString() { if (isNumber()) { return getAsNumber().toString(); } else if (isBoolean()) { return getAsBooleanWrapper().toString(); } else { return (String) value; } } /** * convenience method to get this element as a primitive double. * * @return get this element as a primitive double. * @throws NumberFormatException if the value contained is not a valid double. */ @Override public double getAsDouble() { return isNumber() ? getAsNumber().doubleValue() : Double.parseDouble(getAsString()); } /** * convenience method to get this element as a {@link BigDecimal}. * * @return get this element as a {@link BigDecimal}. * @throws NumberFormatException if the value contained is not a valid {@link BigDecimal}. */ @Override public BigDecimal getAsBigDecimal() { return value instanceof BigDecimal ? (BigDecimal) value : new BigDecimal(value.toString()); } /** * convenience method to get this element as a {@link BigInteger}. * * @return get this element as a {@link BigInteger}. * @throws NumberFormatException if the value contained is not a valid {@link BigInteger}. */ @Override public BigInteger getAsBigInteger() { return value instanceof BigInteger ? (BigInteger) value : new BigInteger(value.toString()); } /** * convenience method to get this element as a float. * * @return get this element as a float. * @throws NumberFormatException if the value contained is not a valid float. */ @Override public float getAsFloat() { return isNumber() ? getAsNumber().floatValue() : Float.parseFloat(getAsString()); } /** * convenience method to get this element as a primitive long. * * @return get this element as a primitive long. * @throws NumberFormatException if the value contained is not a valid long. */ @Override public long getAsLong() { return isNumber() ? getAsNumber().longValue() : Long.parseLong(getAsString()); } /** * convenience method to get this element as a primitive short. * * @return get this element as a primitive short. * @throws NumberFormatException if the value contained is not a valid short value. */ @Override public short getAsShort() { return isNumber() ? getAsNumber().shortValue() : Short.parseShort(getAsString()); } /** * convenience method to get this element as a primitive integer. * * @return get this element as a primitive integer. * @throws NumberFormatException if the value contained is not a valid integer. */ @Override public int getAsInt() { return isNumber() ? getAsNumber().intValue() : Integer.parseInt(getAsString()); } @Override public byte getAsByte() { return isNumber() ? getAsNumber().byteValue() : Byte.parseByte(getAsString()); } @Override public char getAsCharacter() { return getAsString().charAt(0); } private static boolean isPrimitiveOrString(Object target) { if (target instanceof String) { return true; } Class classOfPrimitive = target.getClass(); for (Class standardPrimitive : PRIMITIVE_TYPES) { if (standardPrimitive.isAssignableFrom(classOfPrimitive)) { return true; } } return false; } @Override public int hashCode() { if (value == null) { return 31; } // Using recommended hashing algorithm from Effective Java for longs and doubles if (isIntegral(this)) { long value = getAsNumber().longValue(); return (int) (value ^ (value >>> 32)); } if (value instanceof Number) { long value = Double.doubleToLongBits(getAsNumber().doubleValue()); return (int) (value ^ (value >>> 32)); } return value.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } JsonPrimitive other = (JsonPrimitive)obj; if (value == null) { return other.value == null; } if (isIntegral(this) && isIntegral(other)) { return getAsNumber().longValue() == other.getAsNumber().longValue(); } if (value instanceof Number && other.value instanceof Number) { double a = getAsNumber().doubleValue(); // Java standard types other than double return true for two NaN. So, need // special handling for double. double b = other.getAsNumber().doubleValue(); return a == b || (Double.isNaN(a) && Double.isNaN(b)); } return value.equals(other.value); } /** * Returns true if the specified number is an integral type * (Long, Integer, Short, Byte, BigInteger) */ private static boolean isIntegral(JsonPrimitive primitive) { if (primitive.value instanceof Number) { Number number = (Number) primitive.value; return number instanceof BigInteger || number instanceof Long || number instanceof Integer || number instanceof Short || number instanceof Byte; } return false; } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/JsonSerializationContext.java000066400000000000000000000035221316034351600312110ustar00rootroot00000000000000/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson; import java.lang.reflect.Type; /** * Context for serialization that is passed to a custom serializer during invocation of its * {@link JsonSerializer#serialize(Object, Type, JsonSerializationContext)} method. * * @author Inderjeet Singh * @author Joel Leitch */ public interface JsonSerializationContext { /** * Invokes default serialization on the specified object. * * @param src the object that needs to be serialized. * @return a tree of {@link JsonElement}s corresponding to the serialized form of {@code src}. */ public JsonElement serialize(Object src); /** * Invokes default serialization on the specified object passing the specific type information. * It should never be invoked on the element received as a parameter of the * {@link JsonSerializer#serialize(Object, Type, JsonSerializationContext)} method. Doing * so will result in an infinite loop since Gson will in-turn call the custom serializer again. * * @param src the object that needs to be serialized. * @param typeOfSrc the actual genericized type of src object. * @return a tree of {@link JsonElement}s corresponding to the serialized form of {@code src}. */ public JsonElement serialize(Object src, Type typeOfSrc); } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/JsonSerializer.java000066400000000000000000000065311316034351600271430ustar00rootroot00000000000000/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson; import java.lang.reflect.Type; /** * Interface representing a custom serializer for Json. You should write a custom serializer, if * you are not happy with the default serialization done by Gson. You will also need to register * this serializer through {@link com.google.gson.GsonBuilder#registerTypeAdapter(Type, Object)}. * *

Let us look at example where defining a serializer will be useful. The {@code Id} class * defined below has two fields: {@code clazz} and {@code value}.

* *

 * public class Id<T> {
 *   private final Class<T> clazz;
 *   private final long value;
 *
 *   public Id(Class<T> clazz, long value) {
 *     this.clazz = clazz;
 *     this.value = value;
 *   }
 *
 *   public long getValue() {
 *     return value;
 *   }
 * }
 * 

* *

The default serialization of {@code Id(com.foo.MyObject.class, 20L)} will be * {"clazz":com.foo.MyObject,"value":20}. Suppose, you just want the output to be * the value instead, which is {@code 20} in this case. You can achieve that by writing a custom * serializer:

* *

 * class IdSerializer implements JsonSerializer<Id>() {
 *   public JsonElement serialize(Id id, Type typeOfId, JsonSerializationContext context) {
 *     return new JsonPrimitive(id.getValue());
 *   }
 * }
 * 

* *

You will also need to register {@code IdSerializer} with Gson as follows:

*
 * Gson gson = new GsonBuilder().registerTypeAdapter(Id.class, new IdSerializer()).create();
 * 
* *

New applications should prefer {@link TypeAdapter}, whose streaming API * is more efficient than this interface's tree API. * * @author Inderjeet Singh * @author Joel Leitch * * @param type for which the serializer is being registered. It is possible that a serializer * may be asked to serialize a specific generic type of the T. */ public interface JsonSerializer { /** * Gson invokes this call-back method during serialization when it encounters a field of the * specified type. * *

In the implementation of this call-back method, you should consider invoking * {@link JsonSerializationContext#serialize(Object, Type)} method to create JsonElements for any * non-trivial field of the {@code src} object. However, you should never invoke it on the * {@code src} object itself since that will cause an infinite loop (Gson will call your * call-back method again).

* * @param src the object that needs to be converted to Json. * @param typeOfSrc the actual type (fully genericized version) of the source object. * @return a JsonElement corresponding to the specified object. */ public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context); } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/JsonStreamParser.java000066400000000000000000000073341316034351600274440ustar00rootroot00000000000000/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson; import java.io.EOFException; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.Iterator; import java.util.NoSuchElementException; import com.google.gson.internal.Streams; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.MalformedJsonException; /** * A streaming parser that allows reading of multiple {@link JsonElement}s from the specified reader * asynchronously. * *

This class is conditionally thread-safe (see Item 70, Effective Java second edition). To * properly use this class across multiple threads, you will need to add some external * synchronization. For example: * *

 * JsonStreamParser parser = new JsonStreamParser("['first'] {'second':10} 'third'");
 * JsonElement element;
 * synchronized (parser) {  // synchronize on an object shared by threads
 *   if (parser.hasNext()) {
 *     element = parser.next();
 *   }
 * }
 * 
* * @author Inderjeet Singh * @author Joel Leitch * @since 1.4 */ public final class JsonStreamParser implements Iterator { private final JsonReader parser; private final Object lock; /** * @param json The string containing JSON elements concatenated to each other. * @since 1.4 */ public JsonStreamParser(String json) { this(new StringReader(json)); } /** * @param reader The data stream containing JSON elements concatenated to each other. * @since 1.4 */ public JsonStreamParser(Reader reader) { parser = new JsonReader(reader); parser.setLenient(true); lock = new Object(); } /** * Returns the next available {@link JsonElement} on the reader. Null if none available. * * @return the next available {@link JsonElement} on the reader. Null if none available. * @throws JsonParseException if the incoming stream is malformed JSON. * @since 1.4 */ public JsonElement next() throws JsonParseException { if (!hasNext()) { throw new NoSuchElementException(); } try { return Streams.parse(parser); } catch (StackOverflowError e) { throw new JsonParseException("Failed parsing JSON source to Json", e); } catch (OutOfMemoryError e) { throw new JsonParseException("Failed parsing JSON source to Json", e); } catch (JsonParseException e) { throw e.getCause() instanceof EOFException ? new NoSuchElementException() : e; } } /** * Returns true if a {@link JsonElement} is available on the input for consumption * @return true if a {@link JsonElement} is available on the input, false otherwise * @since 1.4 */ public boolean hasNext() { synchronized (lock) { try { return parser.peek() != JsonToken.END_DOCUMENT; } catch (MalformedJsonException e) { throw new JsonSyntaxException(e); } catch (IOException e) { throw new JsonIOException(e); } } } /** * This optional {@link Iterator} method is not relevant for stream parsing and hence is not * implemented. * @since 1.4 */ public void remove() { throw new UnsupportedOperationException(); } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/JsonSyntaxException.java000066400000000000000000000025531316034351600301770ustar00rootroot00000000000000/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson; /** * This exception is raised when Gson attempts to read (or write) a malformed * JSON element. * * @author Inderjeet Singh * @author Joel Leitch */ public final class JsonSyntaxException extends JsonParseException { private static final long serialVersionUID = 1L; public JsonSyntaxException(String msg) { super(msg); } public JsonSyntaxException(String msg, Throwable cause) { super(msg, cause); } /** * Creates exception with the specified cause. Consider using * {@link #JsonSyntaxException(String, Throwable)} instead if you can * describe what actually happened. * * @param cause root exception that caused this exception to be thrown. */ public JsonSyntaxException(Throwable cause) { super(cause); } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/LongSerializationPolicy.java000066400000000000000000000034041316034351600310110ustar00rootroot00000000000000/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson; /** * Defines the expected format for a {@code long} or {@code Long} type when its serialized. * * @since 1.3 * * @author Inderjeet Singh * @author Joel Leitch */ public enum LongSerializationPolicy { /** * This is the "default" serialization policy that will output a {@code long} object as a JSON * number. For example, assume an object has a long field named "f" then the serialized output * would be: * {@code {"f":123}}. */ DEFAULT() { @Override public JsonElement serialize(Long value) { return new JsonPrimitive(value); } }, /** * Serializes a long value as a quoted string. For example, assume an object has a long field * named "f" then the serialized output would be: * {@code {"f":"123"}}. */ STRING() { @Override public JsonElement serialize(Long value) { return new JsonPrimitive(String.valueOf(value)); } }; /** * Serialize this {@code value} using this serialization policy. * * @param value the long value to be serialized into a {@link JsonElement} * @return the serialized version of {@code value} */ public abstract JsonElement serialize(Long value); } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/TypeAdapter.java000066400000000000000000000252321316034351600264210ustar00rootroot00000000000000/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson; import com.google.gson.internal.bind.JsonTreeWriter; import com.google.gson.internal.bind.JsonTreeReader; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; /** * Converts Java objects to and from JSON. * *

Defining a type's JSON form

* By default Gson converts application classes to JSON using its built-in type * adapters. If Gson's default JSON conversion isn't appropriate for a type, * extend this class to customize the conversion. Here's an example of a type * adapter for an (X,Y) coordinate point:
   {@code
 *
 *   public class PointAdapter extends TypeAdapter {
 *     public Point read(JsonReader reader) throws IOException {
 *       if (reader.peek() == JsonToken.NULL) {
 *         reader.nextNull();
 *         return null;
 *       }
 *       String xy = reader.nextString();
 *       String[] parts = xy.split(",");
 *       int x = Integer.parseInt(parts[0]);
 *       int y = Integer.parseInt(parts[1]);
 *       return new Point(x, y);
 *     }
 *     public void write(JsonWriter writer, Point value) throws IOException {
 *       if (value == null) {
 *         writer.nullValue();
 *         return;
 *       }
 *       String xy = value.getX() + "," + value.getY();
 *       writer.value(xy);
 *     }
 *   }}
* With this type adapter installed, Gson will convert {@code Points} to JSON as * strings like {@code "5,8"} rather than objects like {@code {"x":5,"y":8}}. In * this case the type adapter binds a rich Java class to a compact JSON value. * *

The {@link #read(JsonReader) read()} method must read exactly one value * and {@link #write(JsonWriter,Object) write()} must write exactly one value. * For primitive types this is means readers should make exactly one call to * {@code nextBoolean()}, {@code nextDouble()}, {@code nextInt()}, {@code * nextLong()}, {@code nextString()} or {@code nextNull()}. Writers should make * exactly one call to one of value() or nullValue(). * For arrays, type adapters should start with a call to {@code beginArray()}, * convert all elements, and finish with a call to {@code endArray()}. For * objects, they should start with {@code beginObject()}, convert the object, * and finish with {@code endObject()}. Failing to convert a value or converting * too many values may cause the application to crash. * *

Type adapters should be prepared to read null from the stream and write it * to the stream. Alternatively, they should use {@link #nullSafe()} method while * registering the type adapter with Gson. If your {@code Gson} instance * has been configured to {@link GsonBuilder#serializeNulls()}, these nulls will be * written to the final document. Otherwise the value (and the corresponding name * when writing to a JSON object) will be omitted automatically. In either case * your type adapter must handle null. * *

To use a custom type adapter with Gson, you must register it with a * {@link GsonBuilder}:

   {@code
 *
 *   GsonBuilder builder = new GsonBuilder();
 *   builder.registerTypeAdapter(Point.class, new PointAdapter());
 *   // if PointAdapter didn't check for nulls in its read/write methods, you should instead use
 *   // builder.registerTypeAdapter(Point.class, new PointAdapter().nullSafe());
 *   ...
 *   Gson gson = builder.create();
 * }
* * @since 2.1 */ // non-Javadoc: // //

JSON Conversion

//

A type adapter registered with Gson is automatically invoked while serializing // or deserializing JSON. However, you can also use type adapters directly to serialize // and deserialize JSON. Here is an example for deserialization:

   {@code
//
//   String json = "{'origin':'0,0','points':['1,2','3,4']}";
//   TypeAdapter graphAdapter = gson.getAdapter(Graph.class);
//   Graph graph = graphAdapter.fromJson(json);
// }
// And an example for serialization:
   {@code
//
//   Graph graph = new Graph(...);
//   TypeAdapter graphAdapter = gson.getAdapter(Graph.class);
//   String json = graphAdapter.toJson(graph);
// }
// //

Type adapters are type-specific. For example, a {@code // TypeAdapter} can convert {@code Date} instances to JSON and JSON to // instances of {@code Date}, but cannot convert any other types. // public abstract class TypeAdapter { /** * Writes one JSON value (an array, object, string, number, boolean or null) * for {@code value}. * * @param value the Java object to write. May be null. */ public abstract void write(JsonWriter out, T value) throws IOException; /** * Converts {@code value} to a JSON document and writes it to {@code out}. * Unlike Gson's similar {@link Gson#toJson(JsonElement, Appendable) toJson} * method, this write is strict. Create a {@link * JsonWriter#setLenient(boolean) lenient} {@code JsonWriter} and call * {@link #write(com.google.gson.stream.JsonWriter, Object)} for lenient * writing. * * @param value the Java object to convert. May be null. * @since 2.2 */ public final void toJson(Writer out, T value) throws IOException { JsonWriter writer = new JsonWriter(out); write(writer, value); } /** * This wrapper method is used to make a type adapter null tolerant. In general, a * type adapter is required to handle nulls in write and read methods. Here is how this * is typically done:
*

   {@code
   *
   * Gson gson = new GsonBuilder().registerTypeAdapter(Foo.class,
   *   new TypeAdapter() {
   *     public Foo read(JsonReader in) throws IOException {
   *       if (in.peek() == JsonToken.NULL) {
   *         in.nextNull();
   *         return null;
   *       }
   *       // read a Foo from in and return it
   *     }
   *     public void write(JsonWriter out, Foo src) throws IOException {
   *       if (src == null) {
   *         out.nullValue();
   *         return;
   *       }
   *       // write src as JSON to out
   *     }
   *   }).create();
   * }
* You can avoid this boilerplate handling of nulls by wrapping your type adapter with * this method. Here is how we will rewrite the above example: *
   {@code
   *
   * Gson gson = new GsonBuilder().registerTypeAdapter(Foo.class,
   *   new TypeAdapter() {
   *     public Foo read(JsonReader in) throws IOException {
   *       // read a Foo from in and return it
   *     }
   *     public void write(JsonWriter out, Foo src) throws IOException {
   *       // write src as JSON to out
   *     }
   *   }.nullSafe()).create();
   * }
* Note that we didn't need to check for nulls in our type adapter after we used nullSafe. */ public final TypeAdapter nullSafe() { return new TypeAdapter() { @Override public void write(JsonWriter out, T value) throws IOException { if (value == null) { out.nullValue(); } else { TypeAdapter.this.write(out, value); } } @Override public T read(JsonReader reader) throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return null; } return TypeAdapter.this.read(reader); } }; } /** * Converts {@code value} to a JSON document. Unlike Gson's similar {@link * Gson#toJson(Object) toJson} method, this write is strict. Create a {@link * JsonWriter#setLenient(boolean) lenient} {@code JsonWriter} and call * {@link #write(com.google.gson.stream.JsonWriter, Object)} for lenient * writing. * * @param value the Java object to convert. May be null. * @since 2.2 */ public final String toJson(T value) { StringWriter stringWriter = new StringWriter(); try { toJson(stringWriter, value); } catch (IOException e) { throw new AssertionError(e); // No I/O writing to a StringWriter. } return stringWriter.toString(); } /** * Converts {@code value} to a JSON tree. * * @param value the Java object to convert. May be null. * @return the converted JSON tree. May be {@link JsonNull}. * @since 2.2 */ public final JsonElement toJsonTree(T value) { try { JsonTreeWriter jsonWriter = new JsonTreeWriter(); write(jsonWriter, value); return jsonWriter.get(); } catch (IOException e) { throw new JsonIOException(e); } } /** * Reads one JSON value (an array, object, string, number, boolean or null) * and converts it to a Java object. Returns the converted object. * * @return the converted Java object. May be null. */ public abstract T read(JsonReader in) throws IOException; /** * Converts the JSON document in {@code in} to a Java object. Unlike Gson's * similar {@link Gson#fromJson(java.io.Reader, Class) fromJson} method, this * read is strict. Create a {@link JsonReader#setLenient(boolean) lenient} * {@code JsonReader} and call {@link #read(JsonReader)} for lenient reading. * * @return the converted Java object. May be null. * @since 2.2 */ public final T fromJson(Reader in) throws IOException { JsonReader reader = new JsonReader(in); return read(reader); } /** * Converts the JSON document in {@code json} to a Java object. Unlike Gson's * similar {@link Gson#fromJson(String, Class) fromJson} method, this read is * strict. Create a {@link JsonReader#setLenient(boolean) lenient} {@code * JsonReader} and call {@link #read(JsonReader)} for lenient reading. * * @return the converted Java object. May be null. * @since 2.2 */ public final T fromJson(String json) throws IOException { return fromJson(new StringReader(json)); } /** * Converts {@code jsonTree} to a Java object. * * @param jsonTree the Java object to convert. May be {@link JsonNull}. * @since 2.2 */ public final T fromJsonTree(JsonElement jsonTree) { try { JsonReader jsonReader = new JsonTreeReader(jsonTree); return read(jsonReader); } catch (IOException e) { throw new JsonIOException(e); } } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/TypeAdapterFactory.java000066400000000000000000000146761316034351600277630ustar00rootroot00000000000000/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson; import com.google.gson.reflect.TypeToken; /** * Creates type adapters for set of related types. Type adapter factories are * most useful when several types share similar structure in their JSON form. * *

Example: Converting enums to lowercase

* In this example, we implement a factory that creates type adapters for all * enums. The type adapters will write enums in lowercase, despite the fact * that they're defined in {@code CONSTANT_CASE} in the corresponding Java * model:
   {@code
 *
 *   public class LowercaseEnumTypeAdapterFactory implements TypeAdapterFactory {
 *     public  TypeAdapter create(Gson gson, TypeToken type) {
 *       Class rawType = (Class) type.getRawType();
 *       if (!rawType.isEnum()) {
 *         return null;
 *       }
 *
 *       final Map lowercaseToConstant = new HashMap();
 *       for (T constant : rawType.getEnumConstants()) {
 *         lowercaseToConstant.put(toLowercase(constant), constant);
 *       }
 *
 *       return new TypeAdapter() {
 *         public void write(JsonWriter out, T value) throws IOException {
 *           if (value == null) {
 *             out.nullValue();
 *           } else {
 *             out.value(toLowercase(value));
 *           }
 *         }
 *
 *         public T read(JsonReader reader) throws IOException {
 *           if (reader.peek() == JsonToken.NULL) {
 *             reader.nextNull();
 *             return null;
 *           } else {
 *             return lowercaseToConstant.get(reader.nextString());
 *           }
 *         }
 *       };
 *     }
 *
 *     private String toLowercase(Object o) {
 *       return o.toString().toLowerCase(Locale.US);
 *     }
 *   }
 * }
* *

Type adapter factories select which types they provide type adapters * for. If a factory cannot support a given type, it must return null when * that type is passed to {@link #create}. Factories should expect {@code * create()} to be called on them for many types and should return null for * most of those types. In the above example the factory returns null for * calls to {@code create()} where {@code type} is not an enum. * *

A factory is typically called once per type, but the returned type * adapter may be used many times. It is most efficient to do expensive work * like reflection in {@code create()} so that the type adapter's {@code * read()} and {@code write()} methods can be very fast. In this example the * mapping from lowercase name to enum value is computed eagerly. * *

As with type adapters, factories must be registered with a {@link * com.google.gson.GsonBuilder} for them to take effect:

   {@code
 *
 *  GsonBuilder builder = new GsonBuilder();
 *  builder.registerTypeAdapterFactory(new LowercaseEnumTypeAdapterFactory());
 *  ...
 *  Gson gson = builder.create();
 * }
* If multiple factories support the same type, the factory registered earlier * takes precedence. * *

Example: composing other type adapters

* In this example we implement a factory for Guava's {@code Multiset} * collection type. The factory can be used to create type adapters for * multisets of any element type: the type adapter for {@code * Multiset} is different from the type adapter for {@code * Multiset}. * *

The type adapter delegates to another type adapter for the * multiset elements. It figures out the element type by reflecting on the * multiset's type token. A {@code Gson} is passed in to {@code create} for * just this purpose:

   {@code
 *
 *   public class MultisetTypeAdapterFactory implements TypeAdapterFactory {
 *     public  TypeAdapter create(Gson gson, TypeToken typeToken) {
 *       Type type = typeToken.getType();
 *       if (typeToken.getRawType() != Multiset.class
 *           || !(type instanceof ParameterizedType)) {
 *         return null;
 *       }
 *
 *       Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0];
 *       TypeAdapter elementAdapter = gson.getAdapter(TypeToken.get(elementType));
 *       return (TypeAdapter) newMultisetAdapter(elementAdapter);
 *     }
 *
 *     private  TypeAdapter> newMultisetAdapter(
 *         final TypeAdapter elementAdapter) {
 *       return new TypeAdapter>() {
 *         public void write(JsonWriter out, Multiset value) throws IOException {
 *           if (value == null) {
 *             out.nullValue();
 *             return;
 *           }
 *
 *           out.beginArray();
 *           for (Multiset.Entry entry : value.entrySet()) {
 *             out.value(entry.getCount());
 *             elementAdapter.write(out, entry.getElement());
 *           }
 *           out.endArray();
 *         }
 *
 *         public Multiset read(JsonReader in) throws IOException {
 *           if (in.peek() == JsonToken.NULL) {
 *             in.nextNull();
 *             return null;
 *           }
 *
 *           Multiset result = LinkedHashMultiset.create();
 *           in.beginArray();
 *           while (in.hasNext()) {
 *             int count = in.nextInt();
 *             E element = elementAdapter.read(in);
 *             result.add(element, count);
 *           }
 *           in.endArray();
 *           return result;
 *         }
 *       };
 *     }
 *   }
 * }
* Delegating from one type adapter to another is extremely powerful; it's * the foundation of how Gson converts Java objects and collections. Whenever * possible your factory should retrieve its delegate type adapter in the * {@code create()} method; this ensures potentially-expensive type adapter * creation happens only once. * * @since 2.1 */ public interface TypeAdapterFactory { /** * Returns a type adapter for {@code type}, or null if this factory doesn't * support {@code type}. */ TypeAdapter create(Gson gson, TypeToken type); } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/annotations/000077500000000000000000000000001316034351600256655ustar00rootroot00000000000000gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/annotations/Expose.java000066400000000000000000000066741316034351600300100ustar00rootroot00000000000000/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * An annotation that indicates this member should be exposed for JSON * serialization or deserialization. * *

This annotation has no effect unless you build {@link com.google.gson.Gson} * with a {@link com.google.gson.GsonBuilder} and invoke * {@link com.google.gson.GsonBuilder#excludeFieldsWithoutExposeAnnotation()} * method.

* *

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

 * public class User {
 *   @Expose private String firstName;
 *   @Expose(serialize = false) private String lastName;
 *   @Expose (serialize = false, deserialize = false) private String emailAddress;
 *   private String password;
 * }
 * 

* If you created Gson with {@code new Gson()}, the {@code toJson()} and {@code fromJson()} * methods will use the {@code password} field along-with {@code firstName}, {@code lastName}, * and {@code emailAddress} for serialization and deserialization. However, if you created Gson * with {@code Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()} * then the {@code toJson()} and {@code fromJson()} methods of Gson will exclude the * {@code password} field. This is because the {@code password} field is not marked with the * {@code @Expose} annotation. Gson will also exclude {@code lastName} and {@code emailAddress} * from serialization since {@code serialize} is set to {@code false}. Similarly, Gson will * exclude {@code emailAddress} from deserialization since {@code deserialize} is set to false. * *

Note that another way to achieve the same effect would have been to just mark the * {@code password} field as {@code transient}, and Gson would have excluded it even with default * settings. The {@code @Expose} annotation is useful in a style of programming where you want to * explicitly specify all fields that should get considered for serialization or deserialization. * * @author Inderjeet Singh * @author Joel Leitch */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Expose { /** * If {@code true}, the field marked with this annotation is written out in the JSON while * serializing. If {@code false}, the field marked with this annotation is skipped from the * serialized output. Defaults to {@code true}. * @since 1.4 */ public boolean serialize() default true; /** * If {@code true}, the field marked with this annotation is deserialized from the JSON. * If {@code false}, the field marked with this annotation is skipped during deserialization. * Defaults to {@code true}. * @since 1.4 */ public boolean deserialize() default true; } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/annotations/JsonAdapter.java000066400000000000000000000072011316034351600307420ustar00rootroot00000000000000/* * Copyright (C) 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.annotations; import com.google.gson.JsonDeserializer; import com.google.gson.JsonSerializer; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * An annotation that indicates the Gson {@link TypeAdapter} to use with a class * or field. * *

Here is an example of how this annotation is used:

*
 * @JsonAdapter(UserJsonAdapter.class)
 * public class User {
 *   public final String firstName, lastName;
 *   private User(String firstName, String lastName) {
 *     this.firstName = firstName;
 *     this.lastName = lastName;
 *   }
 * }
 * public class UserJsonAdapter extends TypeAdapter<User> {
 *   @Override public void write(JsonWriter out, User user) throws IOException {
 *     // implement write: combine firstName and lastName into name
 *     out.beginObject();
 *     out.name("name");
 *     out.value(user.firstName + " " + user.lastName);
 *     out.endObject();
 *     // implement the write method
 *   }
 *   @Override public User read(JsonReader in) throws IOException {
 *     // implement read: split name into firstName and lastName
 *     in.beginObject();
 *     in.nextName();
 *     String[] nameParts = in.nextString().split(" ");
 *     in.endObject();
 *     return new User(nameParts[0], nameParts[1]);
 *   }
 * }
 * 
* * Since User class specified UserJsonAdapter.class in @JsonAdapter annotation, it * will automatically be invoked to serialize/deserialize User instances.
* *

Here is an example of how to apply this annotation to a field. *

 * private static final class Gadget {
 *   @JsonAdapter(UserJsonAdapter2.class)
 *   final User user;
 *   Gadget(User user) {
 *     this.user = user;
 *   }
 * }
 * 
* * It's possible to specify different type adapters on a field, that * field's type, and in the {@link com.google.gson.GsonBuilder}. Field * annotations take precedence over {@code GsonBuilder}-registered type * adapters, which in turn take precedence over annotated types. * *

The class referenced by this annotation must be either a {@link * TypeAdapter} or a {@link TypeAdapterFactory}, or must implement one * or both of {@link JsonDeserializer} or {@link JsonSerializer}. * Using {@link TypeAdapterFactory} makes it possible to delegate * to the enclosing {@code Gson} instance. * * @since 2.3 * * @author Inderjeet Singh * @author Joel Leitch * @author Jesse Wilson */ // Note that the above example is taken from AdaptAnnotationTest. @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.FIELD}) public @interface JsonAdapter { /** Either a {@link TypeAdapter} or {@link TypeAdapterFactory}, or one or both of {@link JsonDeserializer} or {@link JsonSerializer}. */ Class value(); /** false, to be able to handle {@code null} values within the adapter, default value is true. */ boolean nullSafe() default true; } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/annotations/SerializedName.java000066400000000000000000000061441316034351600314310ustar00rootroot00000000000000/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * An annotation that indicates this member should be serialized to JSON with * the provided name value as its field name. * *

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

* *

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

*
 * public class MyClass {
 *   @SerializedName("name") String a;
 *   @SerializedName(value="name1", alternate={"name2", "name3"}) String b;
 *   String c;
 *
 *   public MyClass(String a, String b, String c) {
 *     this.a = a;
 *     this.b = b;
 *     this.c = c;
 *   }
 * }
 * 
* *

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

*
 * MyClass target = new MyClass("v1", "v2", "v3");
 * Gson gson = new Gson();
 * String json = gson.toJson(target);
 * System.out.println(json);
 *
 * ===== OUTPUT =====
 * {"name":"v1","name1":"v2","c":"v3"}
 * 
* *

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

* While deserializing, all values specified in the annotation will be deserialized into the field. * For example: *
 *   MyClass target = gson.fromJson("{'name1':'v1'}", MyClass.class);
 *   assertEquals("v1", target.b);
 *   target = gson.fromJson("{'name2':'v2'}", MyClass.class);
 *   assertEquals("v2", target.b);
 *   target = gson.fromJson("{'name3':'v3'}", MyClass.class);
 *   assertEquals("v3", target.b);
 * 
* Note that MyClass.b is now deserialized from either name1, name2 or name3. * * @see com.google.gson.FieldNamingPolicy * * @author Inderjeet Singh * @author Joel Leitch */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD}) public @interface SerializedName { /** * @return the desired name of the field when it is serialized or deserialized */ String value(); /** * @return the alternative names of the field when it is deserialized */ String[] alternate() default {}; } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/annotations/Since.java000066400000000000000000000043701316034351600275750ustar00rootroot00000000000000/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * An annotation that indicates the version number since a member or a type has been present. * This annotation is useful to manage versioning of your Json classes for a web-service. * *

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

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

*
 * public class User {
 *   private String firstName;
 *   private String lastName;
 *   @Since(1.0) private String emailAddress;
 *   @Since(1.0) private String password;
 *   @Since(1.1) private Address address;
 * }
 * 
* *

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

* * @author Inderjeet Singh * @author Joel Leitch */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.TYPE}) public @interface Since { /** * the value indicating a version number since this member * or type has been present. */ double value(); } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/annotations/Until.java000066400000000000000000000050611316034351600276250ustar00rootroot00000000000000/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * An annotation that indicates the version number until a member or a type should be present. * Basically, if Gson is created with a version number that exceeds the value stored in the * {@code Until} annotation then the field will be ignored from the JSON output. This annotation * is useful to manage versioning of your JSON classes for a web-service. * *

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

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

*
 * public class User {
 *   private String firstName;
 *   private String lastName;
 *   @Until(1.1) private String emailAddress;
 *   @Until(1.1) private String password;
 * }
 * 
* *

If you created Gson with {@code new Gson()}, the {@code toJson()} and {@code fromJson()} * methods will use all the fields for serialization and deserialization. However, if you created * Gson with {@code Gson gson = new GsonBuilder().setVersion(1.2).create()} then the * {@code toJson()} and {@code fromJson()} methods of Gson will exclude the {@code emailAddress} * and {@code password} fields from the example above, because the version number passed to the * GsonBuilder, {@code 1.2}, exceeds the version number set on the {@code Until} annotation, * {@code 1.1}, for those fields. * * @author Inderjeet Singh * @author Joel Leitch * @since 1.3 */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.TYPE}) public @interface Until { /** * the value indicating a version number until this member * or type should be ignored. */ double value(); } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/annotations/package-info.java000066400000000000000000000002611316034351600310530ustar00rootroot00000000000000/** * This package provides annotations that can be used with {@link com.google.gson.Gson}. * * @author Inderjeet Singh, Joel Leitch */ package com.google.gson.annotations;gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/internal/000077500000000000000000000000001316034351600251445ustar00rootroot00000000000000gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/internal/$Gson$Preconditions.java000066400000000000000000000024751316034351600315760ustar00rootroot00000000000000/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.internal; /** * A simple utility class used to check method Preconditions. * *

 * public long divideBy(long value) {
 *   Preconditions.checkArgument(value != 0);
 *   return this.value / value;
 * }
 * 
* * @author Inderjeet Singh * @author Joel Leitch */ public final class $Gson$Preconditions { private $Gson$Preconditions() { throw new UnsupportedOperationException(); } public static T checkNotNull(T obj) { if (obj == null) { throw new NullPointerException(); } return obj; } public static void checkArgument(boolean condition) { if (!condition) { throw new IllegalArgumentException(); } } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/internal/$Gson$Types.java000066400000000000000000000522551316034351600300630ustar00rootroot00000000000000/** * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.internal; import java.io.Serializable; import java.lang.reflect.Array; import java.lang.reflect.GenericArrayType; import java.lang.reflect.GenericDeclaration; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.*; import static com.google.gson.internal.$Gson$Preconditions.checkArgument; import static com.google.gson.internal.$Gson$Preconditions.checkNotNull; /** * Static methods for working with types. * * @author Bob Lee * @author Jesse Wilson */ public final class $Gson$Types { static final Type[] EMPTY_TYPE_ARRAY = new Type[] {}; private $Gson$Types() { throw new UnsupportedOperationException(); } /** * Returns a new parameterized type, applying {@code typeArguments} to * {@code rawType} and enclosed by {@code ownerType}. * * @return a {@link java.io.Serializable serializable} parameterized type. */ public static ParameterizedType newParameterizedTypeWithOwner( Type ownerType, Type rawType, Type... typeArguments) { return new ParameterizedTypeImpl(ownerType, rawType, typeArguments); } /** * Returns an array type whose elements are all instances of * {@code componentType}. * * @return a {@link java.io.Serializable serializable} generic array type. */ public static GenericArrayType arrayOf(Type componentType) { return new GenericArrayTypeImpl(componentType); } /** * Returns a type that represents an unknown type that extends {@code bound}. * For example, if {@code bound} is {@code CharSequence.class}, this returns * {@code ? extends CharSequence}. If {@code bound} is {@code Object.class}, * this returns {@code ?}, which is shorthand for {@code ? extends Object}. */ public static WildcardType subtypeOf(Type bound) { Type[] upperBounds; if (bound instanceof WildcardType) { upperBounds = ((WildcardType) bound).getUpperBounds(); } else { upperBounds = new Type[] { bound }; } return new WildcardTypeImpl(upperBounds, EMPTY_TYPE_ARRAY); } /** * Returns a type that represents an unknown supertype of {@code bound}. For * example, if {@code bound} is {@code String.class}, this returns {@code ? * super String}. */ public static WildcardType supertypeOf(Type bound) { Type[] lowerBounds; if (bound instanceof WildcardType) { lowerBounds = ((WildcardType) bound).getLowerBounds(); } else { lowerBounds = new Type[] { bound }; } return new WildcardTypeImpl(new Type[] { Object.class }, lowerBounds); } /** * Returns a type that is functionally equal but not necessarily equal * according to {@link Object#equals(Object) Object.equals()}. The returned * type is {@link java.io.Serializable}. */ public static Type canonicalize(Type type) { if (type instanceof Class) { Class c = (Class) type; return c.isArray() ? new GenericArrayTypeImpl(canonicalize(c.getComponentType())) : c; } else if (type instanceof ParameterizedType) { ParameterizedType p = (ParameterizedType) type; return new ParameterizedTypeImpl(p.getOwnerType(), p.getRawType(), p.getActualTypeArguments()); } else if (type instanceof GenericArrayType) { GenericArrayType g = (GenericArrayType) type; return new GenericArrayTypeImpl(g.getGenericComponentType()); } else if (type instanceof WildcardType) { WildcardType w = (WildcardType) type; return new WildcardTypeImpl(w.getUpperBounds(), w.getLowerBounds()); } else { // type is either serializable as-is or unsupported return type; } } public static Class getRawType(Type type) { if (type instanceof Class) { // type is a normal class. return (Class) type; } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; // I'm not exactly sure why getRawType() returns Type instead of Class. // Neal isn't either but suspects some pathological case related // to nested classes exists. Type rawType = parameterizedType.getRawType(); checkArgument(rawType instanceof Class); return (Class) rawType; } else if (type instanceof GenericArrayType) { Type componentType = ((GenericArrayType)type).getGenericComponentType(); return Array.newInstance(getRawType(componentType), 0).getClass(); } else if (type instanceof TypeVariable) { // we could use the variable's bounds, but that won't work if there are multiple. // having a raw type that's more general than necessary is okay return Object.class; } else if (type instanceof WildcardType) { return getRawType(((WildcardType) type).getUpperBounds()[0]); } else { String className = type == null ? "null" : type.getClass().getName(); throw new IllegalArgumentException("Expected a Class, ParameterizedType, or " + "GenericArrayType, but <" + type + "> is of type " + className); } } static boolean equal(Object a, Object b) { return a == b || (a != null && a.equals(b)); } /** * Returns true if {@code a} and {@code b} are equal. */ public static boolean equals(Type a, Type b) { if (a == b) { // also handles (a == null && b == null) return true; } else if (a instanceof Class) { // Class already specifies equals(). return a.equals(b); } else if (a instanceof ParameterizedType) { if (!(b instanceof ParameterizedType)) { return false; } // TODO: save a .clone() call ParameterizedType pa = (ParameterizedType) a; ParameterizedType pb = (ParameterizedType) b; return equal(pa.getOwnerType(), pb.getOwnerType()) && pa.getRawType().equals(pb.getRawType()) && Arrays.equals(pa.getActualTypeArguments(), pb.getActualTypeArguments()); } else if (a instanceof GenericArrayType) { if (!(b instanceof GenericArrayType)) { return false; } GenericArrayType ga = (GenericArrayType) a; GenericArrayType gb = (GenericArrayType) b; return equals(ga.getGenericComponentType(), gb.getGenericComponentType()); } else if (a instanceof WildcardType) { if (!(b instanceof WildcardType)) { return false; } WildcardType wa = (WildcardType) a; WildcardType wb = (WildcardType) b; return Arrays.equals(wa.getUpperBounds(), wb.getUpperBounds()) && Arrays.equals(wa.getLowerBounds(), wb.getLowerBounds()); } else if (a instanceof TypeVariable) { if (!(b instanceof TypeVariable)) { return false; } TypeVariable va = (TypeVariable) a; TypeVariable vb = (TypeVariable) b; return va.getGenericDeclaration() == vb.getGenericDeclaration() && va.getName().equals(vb.getName()); } else { // This isn't a type we support. Could be a generic array type, wildcard type, etc. return false; } } static int hashCodeOrZero(Object o) { return o != null ? o.hashCode() : 0; } public static String typeToString(Type type) { return type instanceof Class ? ((Class) type).getName() : type.toString(); } /** * Returns the generic supertype for {@code supertype}. For example, given a class {@code * IntegerSet}, the result for when supertype is {@code Set.class} is {@code Set} and the * result when the supertype is {@code Collection.class} is {@code Collection}. */ static Type getGenericSupertype(Type context, Class rawType, Class toResolve) { if (toResolve == rawType) { return context; } // we skip searching through interfaces if unknown is an interface if (toResolve.isInterface()) { Class[] interfaces = rawType.getInterfaces(); for (int i = 0, length = interfaces.length; i < length; i++) { if (interfaces[i] == toResolve) { return rawType.getGenericInterfaces()[i]; } else if (toResolve.isAssignableFrom(interfaces[i])) { return getGenericSupertype(rawType.getGenericInterfaces()[i], interfaces[i], toResolve); } } } // check our supertypes if (!rawType.isInterface()) { while (rawType != Object.class) { Class rawSupertype = rawType.getSuperclass(); if (rawSupertype == toResolve) { return rawType.getGenericSuperclass(); } else if (toResolve.isAssignableFrom(rawSupertype)) { return getGenericSupertype(rawType.getGenericSuperclass(), rawSupertype, toResolve); } rawType = rawSupertype; } } // we can't resolve this further return toResolve; } /** * Returns the generic form of {@code supertype}. For example, if this is {@code * ArrayList}, this returns {@code Iterable} given the input {@code * Iterable.class}. * * @param supertype a superclass of, or interface implemented by, this. */ static Type getSupertype(Type context, Class contextRawType, Class supertype) { checkArgument(supertype.isAssignableFrom(contextRawType)); return resolve(context, contextRawType, $Gson$Types.getGenericSupertype(context, contextRawType, supertype)); } /** * Returns the component type of this array type. * @throws ClassCastException if this type is not an array. */ public static Type getArrayComponentType(Type array) { return array instanceof GenericArrayType ? ((GenericArrayType) array).getGenericComponentType() : ((Class) array).getComponentType(); } /** * Returns the element type of this collection type. * @throws IllegalArgumentException if this type is not a collection. */ public static Type getCollectionElementType(Type context, Class contextRawType) { Type collectionType = getSupertype(context, contextRawType, Collection.class); if (collectionType instanceof WildcardType) { collectionType = ((WildcardType)collectionType).getUpperBounds()[0]; } if (collectionType instanceof ParameterizedType) { return ((ParameterizedType) collectionType).getActualTypeArguments()[0]; } return Object.class; } /** * Returns a two element array containing this map's key and value types in * positions 0 and 1 respectively. */ public static Type[] getMapKeyAndValueTypes(Type context, Class contextRawType) { /* * Work around a problem with the declaration of java.util.Properties. That * class should extend Hashtable, but it's declared to * extend Hashtable. */ if (context == Properties.class) { return new Type[] { String.class, String.class }; // TODO: test subclasses of Properties! } Type mapType = getSupertype(context, contextRawType, Map.class); // TODO: strip wildcards? if (mapType instanceof ParameterizedType) { ParameterizedType mapParameterizedType = (ParameterizedType) mapType; return mapParameterizedType.getActualTypeArguments(); } return new Type[] { Object.class, Object.class }; } public static Type resolve(Type context, Class contextRawType, Type toResolve) { return resolve(context, contextRawType, toResolve, new HashSet()); } private static Type resolve(Type context, Class contextRawType, Type toResolve, Collection visitedTypeVariables) { // this implementation is made a little more complicated in an attempt to avoid object-creation while (true) { if (toResolve instanceof TypeVariable) { TypeVariable typeVariable = (TypeVariable) toResolve; if (visitedTypeVariables.contains(typeVariable)) { // cannot reduce due to infinite recursion return toResolve; } else { visitedTypeVariables.add(typeVariable); } toResolve = resolveTypeVariable(context, contextRawType, typeVariable); if (toResolve == typeVariable) { return toResolve; } } else if (toResolve instanceof Class && ((Class) toResolve).isArray()) { Class original = (Class) toResolve; Type componentType = original.getComponentType(); Type newComponentType = resolve(context, contextRawType, componentType, visitedTypeVariables); return componentType == newComponentType ? original : arrayOf(newComponentType); } else if (toResolve instanceof GenericArrayType) { GenericArrayType original = (GenericArrayType) toResolve; Type componentType = original.getGenericComponentType(); Type newComponentType = resolve(context, contextRawType, componentType, visitedTypeVariables); return componentType == newComponentType ? original : arrayOf(newComponentType); } else if (toResolve instanceof ParameterizedType) { ParameterizedType original = (ParameterizedType) toResolve; Type ownerType = original.getOwnerType(); Type newOwnerType = resolve(context, contextRawType, ownerType, visitedTypeVariables); boolean changed = newOwnerType != ownerType; Type[] args = original.getActualTypeArguments(); for (int t = 0, length = args.length; t < length; t++) { Type resolvedTypeArgument = resolve(context, contextRawType, args[t], visitedTypeVariables); if (resolvedTypeArgument != args[t]) { if (!changed) { args = args.clone(); changed = true; } args[t] = resolvedTypeArgument; } } return changed ? newParameterizedTypeWithOwner(newOwnerType, original.getRawType(), args) : original; } else if (toResolve instanceof WildcardType) { WildcardType original = (WildcardType) toResolve; Type[] originalLowerBound = original.getLowerBounds(); Type[] originalUpperBound = original.getUpperBounds(); if (originalLowerBound.length == 1) { Type lowerBound = resolve(context, contextRawType, originalLowerBound[0], visitedTypeVariables); if (lowerBound != originalLowerBound[0]) { return supertypeOf(lowerBound); } } else if (originalUpperBound.length == 1) { Type upperBound = resolve(context, contextRawType, originalUpperBound[0], visitedTypeVariables); if (upperBound != originalUpperBound[0]) { return subtypeOf(upperBound); } } return original; } else { return toResolve; } } } static Type resolveTypeVariable(Type context, Class contextRawType, TypeVariable unknown) { Class declaredByRaw = declaringClassOf(unknown); // we can't reduce this further if (declaredByRaw == null) { return unknown; } Type declaredBy = getGenericSupertype(context, contextRawType, declaredByRaw); if (declaredBy instanceof ParameterizedType) { int index = indexOf(declaredByRaw.getTypeParameters(), unknown); return ((ParameterizedType) declaredBy).getActualTypeArguments()[index]; } return unknown; } private static int indexOf(Object[] array, Object toFind) { for (int i = 0, length = array.length; i < length; i++) { if (toFind.equals(array[i])) { return i; } } throw new NoSuchElementException(); } /** * Returns the declaring class of {@code typeVariable}, or {@code null} if it was not declared by * a class. */ private static Class declaringClassOf(TypeVariable typeVariable) { GenericDeclaration genericDeclaration = typeVariable.getGenericDeclaration(); return genericDeclaration instanceof Class ? (Class) genericDeclaration : null; } static void checkNotPrimitive(Type type) { checkArgument(!(type instanceof Class) || !((Class) type).isPrimitive()); } private static final class ParameterizedTypeImpl implements ParameterizedType, Serializable { private final Type ownerType; private final Type rawType; private final Type[] typeArguments; public ParameterizedTypeImpl(Type ownerType, Type rawType, Type... typeArguments) { // require an owner type if the raw type needs it if (rawType instanceof Class) { Class rawTypeAsClass = (Class) rawType; boolean isStaticOrTopLevelClass = Modifier.isStatic(rawTypeAsClass.getModifiers()) || rawTypeAsClass.getEnclosingClass() == null; checkArgument(ownerType != null || isStaticOrTopLevelClass); } this.ownerType = ownerType == null ? null : canonicalize(ownerType); this.rawType = canonicalize(rawType); this.typeArguments = typeArguments.clone(); for (int t = 0, length = this.typeArguments.length; t < length; t++) { checkNotNull(this.typeArguments[t]); checkNotPrimitive(this.typeArguments[t]); this.typeArguments[t] = canonicalize(this.typeArguments[t]); } } public Type[] getActualTypeArguments() { return typeArguments.clone(); } public Type getRawType() { return rawType; } public Type getOwnerType() { return ownerType; } @Override public boolean equals(Object other) { return other instanceof ParameterizedType && $Gson$Types.equals(this, (ParameterizedType) other); } @Override public int hashCode() { return Arrays.hashCode(typeArguments) ^ rawType.hashCode() ^ hashCodeOrZero(ownerType); } @Override public String toString() { int length = typeArguments.length; if (length == 0) { return typeToString(rawType); } StringBuilder stringBuilder = new StringBuilder(30 * (length + 1)); stringBuilder.append(typeToString(rawType)).append("<").append(typeToString(typeArguments[0])); for (int i = 1; i < length; i++) { stringBuilder.append(", ").append(typeToString(typeArguments[i])); } return stringBuilder.append(">").toString(); } private static final long serialVersionUID = 0; } private static final class GenericArrayTypeImpl implements GenericArrayType, Serializable { private final Type componentType; public GenericArrayTypeImpl(Type componentType) { this.componentType = canonicalize(componentType); } public Type getGenericComponentType() { return componentType; } @Override public boolean equals(Object o) { return o instanceof GenericArrayType && $Gson$Types.equals(this, (GenericArrayType) o); } @Override public int hashCode() { return componentType.hashCode(); } @Override public String toString() { return typeToString(componentType) + "[]"; } private static final long serialVersionUID = 0; } /** * The WildcardType interface supports multiple upper bounds and multiple * lower bounds. We only support what the Java 6 language needs - at most one * bound. If a lower bound is set, the upper bound must be Object.class. */ private static final class WildcardTypeImpl implements WildcardType, Serializable { private final Type upperBound; private final Type lowerBound; public WildcardTypeImpl(Type[] upperBounds, Type[] lowerBounds) { checkArgument(lowerBounds.length <= 1); checkArgument(upperBounds.length == 1); if (lowerBounds.length == 1) { checkNotNull(lowerBounds[0]); checkNotPrimitive(lowerBounds[0]); checkArgument(upperBounds[0] == Object.class); this.lowerBound = canonicalize(lowerBounds[0]); this.upperBound = Object.class; } else { checkNotNull(upperBounds[0]); checkNotPrimitive(upperBounds[0]); this.lowerBound = null; this.upperBound = canonicalize(upperBounds[0]); } } public Type[] getUpperBounds() { return new Type[] { upperBound }; } public Type[] getLowerBounds() { return lowerBound != null ? new Type[] { lowerBound } : EMPTY_TYPE_ARRAY; } @Override public boolean equals(Object other) { return other instanceof WildcardType && $Gson$Types.equals(this, (WildcardType) other); } @Override public int hashCode() { // this equals Arrays.hashCode(getLowerBounds()) ^ Arrays.hashCode(getUpperBounds()); return (lowerBound != null ? 31 + lowerBound.hashCode() : 1) ^ (31 + upperBound.hashCode()); } @Override public String toString() { if (lowerBound != null) { return "? super " + typeToString(lowerBound); } else if (upperBound == Object.class) { return "?"; } else { return "? extends " + typeToString(upperBound); } } private static final long serialVersionUID = 0; } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/internal/ConstructorConstructor.java000066400000000000000000000202631316034351600326050ustar00rootroot00000000000000/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.internal; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.EnumSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentNavigableMap; import java.util.concurrent.ConcurrentSkipListMap; import com.google.gson.InstanceCreator; import com.google.gson.JsonIOException; import com.google.gson.reflect.TypeToken; /** * Returns a function that can construct an instance of a requested type. */ public final class ConstructorConstructor { private final Map> instanceCreators; public ConstructorConstructor(Map> instanceCreators) { this.instanceCreators = instanceCreators; } public ObjectConstructor get(TypeToken typeToken) { final Type type = typeToken.getType(); final Class rawType = typeToken.getRawType(); // first try an instance creator @SuppressWarnings("unchecked") // types must agree final InstanceCreator typeCreator = (InstanceCreator) instanceCreators.get(type); if (typeCreator != null) { return new ObjectConstructor() { @Override public T construct() { return typeCreator.createInstance(type); } }; } // Next try raw type match for instance creators @SuppressWarnings("unchecked") // types must agree final InstanceCreator rawTypeCreator = (InstanceCreator) instanceCreators.get(rawType); if (rawTypeCreator != null) { return new ObjectConstructor() { @Override public T construct() { return rawTypeCreator.createInstance(type); } }; } ObjectConstructor defaultConstructor = newDefaultConstructor(rawType); if (defaultConstructor != null) { return defaultConstructor; } ObjectConstructor defaultImplementation = newDefaultImplementationConstructor(type, rawType); if (defaultImplementation != null) { return defaultImplementation; } // finally try unsafe return newUnsafeAllocator(type, rawType); } private ObjectConstructor newDefaultConstructor(Class rawType) { try { final Constructor constructor = rawType.getDeclaredConstructor(); if (!constructor.isAccessible()) { constructor.setAccessible(true); } return new ObjectConstructor() { @SuppressWarnings("unchecked") // T is the same raw type as is requested @Override public T construct() { try { Object[] args = null; return (T) constructor.newInstance(args); } catch (InstantiationException e) { // TODO: JsonParseException ? throw new RuntimeException("Failed to invoke " + constructor + " with no args", e); } catch (InvocationTargetException e) { // TODO: don't wrap if cause is unchecked! // TODO: JsonParseException ? throw new RuntimeException("Failed to invoke " + constructor + " with no args", e.getTargetException()); } catch (IllegalAccessException e) { throw new AssertionError(e); } } }; } catch (NoSuchMethodException e) { return null; } } /** * Constructors for common interface types like Map and List and their * subtypes. */ @SuppressWarnings("unchecked") // use runtime checks to guarantee that 'T' is what it is private ObjectConstructor newDefaultImplementationConstructor( final Type type, Class rawType) { if (Collection.class.isAssignableFrom(rawType)) { if (SortedSet.class.isAssignableFrom(rawType)) { return new ObjectConstructor() { @Override public T construct() { return (T) new TreeSet(); } }; } else if (EnumSet.class.isAssignableFrom(rawType)) { return new ObjectConstructor() { @SuppressWarnings("rawtypes") @Override public T construct() { if (type instanceof ParameterizedType) { Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0]; if (elementType instanceof Class) { return (T) EnumSet.noneOf((Class)elementType); } else { throw new JsonIOException("Invalid EnumSet type: " + type.toString()); } } else { throw new JsonIOException("Invalid EnumSet type: " + type.toString()); } } }; } else if (Set.class.isAssignableFrom(rawType)) { return new ObjectConstructor() { @Override public T construct() { return (T) new LinkedHashSet(); } }; } else if (Queue.class.isAssignableFrom(rawType)) { return new ObjectConstructor() { @Override public T construct() { return (T) new ArrayDeque(); } }; } else { return new ObjectConstructor() { @Override public T construct() { return (T) new ArrayList(); } }; } } if (Map.class.isAssignableFrom(rawType)) { if (ConcurrentNavigableMap.class.isAssignableFrom(rawType)) { return new ObjectConstructor() { @Override public T construct() { return (T) new ConcurrentSkipListMap(); } }; } else if (ConcurrentMap.class.isAssignableFrom(rawType)) { return new ObjectConstructor() { @Override public T construct() { return (T) new ConcurrentHashMap(); } }; } else if (SortedMap.class.isAssignableFrom(rawType)) { return new ObjectConstructor() { @Override public T construct() { return (T) new TreeMap(); } }; } else if (type instanceof ParameterizedType && !(String.class.isAssignableFrom( TypeToken.get(((ParameterizedType) type).getActualTypeArguments()[0]).getRawType()))) { return new ObjectConstructor() { @Override public T construct() { return (T) new LinkedHashMap(); } }; } else { return new ObjectConstructor() { @Override public T construct() { return (T) new LinkedTreeMap(); } }; } } return null; } private ObjectConstructor newUnsafeAllocator( final Type type, final Class rawType) { return new ObjectConstructor() { private final UnsafeAllocator unsafeAllocator = UnsafeAllocator.create(); @SuppressWarnings("unchecked") @Override public T construct() { try { Object newInstance = unsafeAllocator.newInstance(rawType); return (T) newInstance; } catch (Exception e) { throw new RuntimeException(("Unable to invoke no-args constructor for " + type + ". " + "Registering an InstanceCreator with Gson for this type may fix this problem."), e); } } }; } @Override public String toString() { return instanceCreators.toString(); } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/internal/Excluder.java000066400000000000000000000167051316034351600275730ustar00rootroot00000000000000/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.internal; import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.annotations.Expose; import com.google.gson.annotations.Since; import com.google.gson.annotations.Until; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * This class selects which fields and types to omit. It is configurable, * supporting version attributes {@link Since} and {@link Until}, modifiers, * synthetic fields, anonymous and local classes, inner classes, and fields with * the {@link Expose} annotation. * *

This class is a type adapter factory; types that are excluded will be * adapted to null. It may delegate to another type adapter if only one * direction is excluded. * * @author Joel Leitch * @author Jesse Wilson */ public final class Excluder implements TypeAdapterFactory, Cloneable { private static final double IGNORE_VERSIONS = -1.0d; public static final Excluder DEFAULT = new Excluder(); private double version = IGNORE_VERSIONS; private int modifiers = Modifier.TRANSIENT | Modifier.STATIC; private boolean serializeInnerClasses = true; private boolean requireExpose; private List serializationStrategies = Collections.emptyList(); private List deserializationStrategies = Collections.emptyList(); @Override protected Excluder clone() { try { return (Excluder) super.clone(); } catch (CloneNotSupportedException e) { throw new AssertionError(e); } } public Excluder withVersion(double ignoreVersionsAfter) { Excluder result = clone(); result.version = ignoreVersionsAfter; return result; } public Excluder withModifiers(int... modifiers) { Excluder result = clone(); result.modifiers = 0; for (int modifier : modifiers) { result.modifiers |= modifier; } return result; } public Excluder disableInnerClassSerialization() { Excluder result = clone(); result.serializeInnerClasses = false; return result; } public Excluder excludeFieldsWithoutExposeAnnotation() { Excluder result = clone(); result.requireExpose = true; return result; } public Excluder withExclusionStrategy(ExclusionStrategy exclusionStrategy, boolean serialization, boolean deserialization) { Excluder result = clone(); if (serialization) { result.serializationStrategies = new ArrayList(serializationStrategies); result.serializationStrategies.add(exclusionStrategy); } if (deserialization) { result.deserializationStrategies = new ArrayList(deserializationStrategies); result.deserializationStrategies.add(exclusionStrategy); } return result; } public TypeAdapter create(final Gson gson, final TypeToken type) { Class rawType = type.getRawType(); final boolean skipSerialize = excludeClass(rawType, true); final boolean skipDeserialize = excludeClass(rawType, false); if (!skipSerialize && !skipDeserialize) { return null; } return new TypeAdapter() { /** The delegate is lazily created because it may not be needed, and creating it may fail. */ private TypeAdapter delegate; @Override public T read(JsonReader in) throws IOException { if (skipDeserialize) { in.skipValue(); return null; } return delegate().read(in); } @Override public void write(JsonWriter out, T value) throws IOException { if (skipSerialize) { out.nullValue(); return; } delegate().write(out, value); } private TypeAdapter delegate() { TypeAdapter d = delegate; return d != null ? d : (delegate = gson.getDelegateAdapter(Excluder.this, type)); } }; } public boolean excludeField(Field field, boolean serialize) { if ((modifiers & field.getModifiers()) != 0) { return true; } if (version != Excluder.IGNORE_VERSIONS && !isValidVersion(field.getAnnotation(Since.class), field.getAnnotation(Until.class))) { return true; } if (field.isSynthetic()) { return true; } if (requireExpose) { Expose annotation = field.getAnnotation(Expose.class); if (annotation == null || (serialize ? !annotation.serialize() : !annotation.deserialize())) { return true; } } if (!serializeInnerClasses && isInnerClass(field.getType())) { return true; } if (isAnonymousOrLocal(field.getType())) { return true; } List list = serialize ? serializationStrategies : deserializationStrategies; if (!list.isEmpty()) { FieldAttributes fieldAttributes = new FieldAttributes(field); for (ExclusionStrategy exclusionStrategy : list) { if (exclusionStrategy.shouldSkipField(fieldAttributes)) { return true; } } } return false; } public boolean excludeClass(Class clazz, boolean serialize) { if (version != Excluder.IGNORE_VERSIONS && !isValidVersion(clazz.getAnnotation(Since.class), clazz.getAnnotation(Until.class))) { return true; } if (!serializeInnerClasses && isInnerClass(clazz)) { return true; } if (isAnonymousOrLocal(clazz)) { return true; } List list = serialize ? serializationStrategies : deserializationStrategies; for (ExclusionStrategy exclusionStrategy : list) { if (exclusionStrategy.shouldSkipClass(clazz)) { return true; } } return false; } private boolean isAnonymousOrLocal(Class clazz) { return !Enum.class.isAssignableFrom(clazz) && (clazz.isAnonymousClass() || clazz.isLocalClass()); } private boolean isInnerClass(Class clazz) { return clazz.isMemberClass() && !isStatic(clazz); } private boolean isStatic(Class clazz) { return (clazz.getModifiers() & Modifier.STATIC) != 0; } private boolean isValidVersion(Since since, Until until) { return isValidSince(since) && isValidUntil(until); } private boolean isValidSince(Since annotation) { if (annotation != null) { double annotationVersion = annotation.value(); if (annotationVersion > version) { return false; } } return true; } private boolean isValidUntil(Until annotation) { if (annotation != null) { double annotationVersion = annotation.value(); if (annotationVersion <= version) { return false; } } return true; } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/internal/JsonReaderInternalAccess.java000066400000000000000000000020501316034351600326570ustar00rootroot00000000000000/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.internal; import com.google.gson.stream.JsonReader; import java.io.IOException; /** * Internal-only APIs of JsonReader available only to other classes in Gson. */ public abstract class JsonReaderInternalAccess { public static JsonReaderInternalAccess INSTANCE; /** * Changes the type of the current property name token to a string value. */ public abstract void promoteNameToValue(JsonReader reader) throws IOException; } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/internal/LazilyParsedNumber.java000066400000000000000000000045261316034351600315720ustar00rootroot00000000000000/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.internal; import java.io.ObjectStreamException; import java.math.BigDecimal; /** * This class holds a number value that is lazily converted to a specific number type * * @author Inderjeet Singh */ public final class LazilyParsedNumber extends Number { private final String value; /** @param value must not be null */ public LazilyParsedNumber(String value) { this.value = value; } @Override public int intValue() { try { return Integer.parseInt(value); } catch (NumberFormatException e) { try { return (int) Long.parseLong(value); } catch (NumberFormatException nfe) { return new BigDecimal(value).intValue(); } } } @Override public long longValue() { try { return Long.parseLong(value); } catch (NumberFormatException e) { return new BigDecimal(value).longValue(); } } @Override public float floatValue() { return Float.parseFloat(value); } @Override public double doubleValue() { return Double.parseDouble(value); } @Override public String toString() { return value; } /** * If somebody is unlucky enough to have to serialize one of these, serialize * it as a BigDecimal so that they won't need Gson on the other side to * deserialize it. */ private Object writeReplace() throws ObjectStreamException { return new BigDecimal(value); } @Override public int hashCode() { return value.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof LazilyParsedNumber) { LazilyParsedNumber other = (LazilyParsedNumber) obj; return value == other.value || value.equals(other.value); } return false; } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/internal/LinkedHashTreeMap.java000066400000000000000000000627131316034351600313100ustar00rootroot00000000000000/* * Copyright (C) 2010 The Android Open Source Project * Copyright (C) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.internal; import java.io.ObjectStreamException; import java.io.Serializable; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Arrays; import java.util.Comparator; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.NoSuchElementException; import java.util.Set; /** * A map of comparable keys to values. Unlike {@code TreeMap}, this class uses * insertion order for iteration order. Comparison order is only used as an * optimization for efficient insertion and removal. * *

This implementation was derived from Android 4.1's TreeMap and * LinkedHashMap classes. */ public final class LinkedHashTreeMap extends AbstractMap implements Serializable { @SuppressWarnings({ "unchecked", "rawtypes" }) // to avoid Comparable>> private static final Comparator NATURAL_ORDER = new Comparator() { public int compare(Comparable a, Comparable b) { return a.compareTo(b); } }; Comparator comparator; Node[] table; final Node header; int size = 0; int modCount = 0; int threshold; /** * Create a natural order, empty tree map whose keys must be mutually * comparable and non-null. */ @SuppressWarnings("unchecked") // unsafe! this assumes K is comparable public LinkedHashTreeMap() { this((Comparator) NATURAL_ORDER); } /** * Create a tree map ordered by {@code comparator}. This map's keys may only * be null if {@code comparator} permits. * * @param comparator the comparator to order elements with, or {@code null} to * use the natural ordering. */ @SuppressWarnings({ "unchecked", "rawtypes" }) // unsafe! if comparator is null, this assumes K is comparable public LinkedHashTreeMap(Comparator comparator) { this.comparator = comparator != null ? comparator : (Comparator) NATURAL_ORDER; this.header = new Node(); this.table = new Node[16]; // TODO: sizing/resizing policies this.threshold = (table.length / 2) + (table.length / 4); // 3/4 capacity } @Override public int size() { return size; } @Override public V get(Object key) { Node node = findByObject(key); return node != null ? node.value : null; } @Override public boolean containsKey(Object key) { return findByObject(key) != null; } @Override public V put(K key, V value) { if (key == null) { throw new NullPointerException("key == null"); } Node created = find(key, true); V result = created.value; created.value = value; return result; } @Override public void clear() { Arrays.fill(table, null); size = 0; modCount++; // Clear all links to help GC Node header = this.header; for (Node e = header.next; e != header; ) { Node next = e.next; e.next = e.prev = null; e = next; } header.next = header.prev = header; } @Override public V remove(Object key) { Node node = removeInternalByKey(key); return node != null ? node.value : null; } /** * Returns the node at or adjacent to the given key, creating it if requested. * * @throws ClassCastException if {@code key} and the tree's keys aren't * mutually comparable. */ Node find(K key, boolean create) { Comparator comparator = this.comparator; Node[] table = this.table; int hash = secondaryHash(key.hashCode()); int index = hash & (table.length - 1); Node nearest = table[index]; int comparison = 0; if (nearest != null) { // Micro-optimization: avoid polymorphic calls to Comparator.compare(). @SuppressWarnings("unchecked") // Throws a ClassCastException below if there's trouble. Comparable comparableKey = (comparator == NATURAL_ORDER) ? (Comparable) key : null; while (true) { comparison = (comparableKey != null) ? comparableKey.compareTo(nearest.key) : comparator.compare(key, nearest.key); // We found the requested key. if (comparison == 0) { return nearest; } // If it exists, the key is in a subtree. Go deeper. Node child = (comparison < 0) ? nearest.left : nearest.right; if (child == null) { break; } nearest = child; } } // The key doesn't exist in this tree. if (!create) { return null; } // Create the node and add it to the tree or the table. Node header = this.header; Node created; if (nearest == null) { // Check that the value is comparable if we didn't do any comparisons. if (comparator == NATURAL_ORDER && !(key instanceof Comparable)) { throw new ClassCastException(key.getClass().getName() + " is not Comparable"); } created = new Node(nearest, key, hash, header, header.prev); table[index] = created; } else { created = new Node(nearest, key, hash, header, header.prev); if (comparison < 0) { // nearest.key is higher nearest.left = created; } else { // comparison > 0, nearest.key is lower nearest.right = created; } rebalance(nearest, true); } if (size++ > threshold) { doubleCapacity(); } modCount++; return created; } @SuppressWarnings("unchecked") Node findByObject(Object key) { try { return key != null ? find((K) key, false) : null; } catch (ClassCastException e) { return null; } } /** * Returns this map's entry that has the same key and value as {@code * entry}, or null if this map has no such entry. * *

This method uses the comparator for key equality rather than {@code * equals}. If this map's comparator isn't consistent with equals (such as * {@code String.CASE_INSENSITIVE_ORDER}), then {@code remove()} and {@code * contains()} will violate the collections API. */ Node findByEntry(Entry entry) { Node mine = findByObject(entry.getKey()); boolean valuesEqual = mine != null && equal(mine.value, entry.getValue()); return valuesEqual ? mine : null; } private boolean equal(Object a, Object b) { return a == b || (a != null && a.equals(b)); } /** * Applies a supplemental hash function to a given hashCode, which defends * against poor quality hash functions. This is critical because HashMap * uses power-of-two length hash tables, that otherwise encounter collisions * for hashCodes that do not differ in lower or upper bits. */ private static int secondaryHash(int h) { // Doug Lea's supplemental hash function h ^= (h >>> 20) ^ (h >>> 12); return h ^ (h >>> 7) ^ (h >>> 4); } /** * Removes {@code node} from this tree, rearranging the tree's structure as * necessary. * * @param unlink true to also unlink this node from the iteration linked list. */ void removeInternal(Node node, boolean unlink) { if (unlink) { node.prev.next = node.next; node.next.prev = node.prev; node.next = node.prev = null; // Help the GC (for performance) } Node left = node.left; Node right = node.right; Node originalParent = node.parent; if (left != null && right != null) { /* * To remove a node with both left and right subtrees, move an * adjacent node from one of those subtrees into this node's place. * * Removing the adjacent node may change this node's subtrees. This * node may no longer have two subtrees once the adjacent node is * gone! */ Node adjacent = (left.height > right.height) ? left.last() : right.first(); removeInternal(adjacent, false); // takes care of rebalance and size-- int leftHeight = 0; left = node.left; if (left != null) { leftHeight = left.height; adjacent.left = left; left.parent = adjacent; node.left = null; } int rightHeight = 0; right = node.right; if (right != null) { rightHeight = right.height; adjacent.right = right; right.parent = adjacent; node.right = null; } adjacent.height = Math.max(leftHeight, rightHeight) + 1; replaceInParent(node, adjacent); return; } else if (left != null) { replaceInParent(node, left); node.left = null; } else if (right != null) { replaceInParent(node, right); node.right = null; } else { replaceInParent(node, null); } rebalance(originalParent, false); size--; modCount++; } Node removeInternalByKey(Object key) { Node node = findByObject(key); if (node != null) { removeInternal(node, true); } return node; } private void replaceInParent(Node node, Node replacement) { Node parent = node.parent; node.parent = null; if (replacement != null) { replacement.parent = parent; } if (parent != null) { if (parent.left == node) { parent.left = replacement; } else { assert (parent.right == node); parent.right = replacement; } } else { int index = node.hash & (table.length - 1); table[index] = replacement; } } /** * Rebalances the tree by making any AVL rotations necessary between the * newly-unbalanced node and the tree's root. * * @param insert true if the node was unbalanced by an insert; false if it * was by a removal. */ private void rebalance(Node unbalanced, boolean insert) { for (Node node = unbalanced; node != null; node = node.parent) { Node left = node.left; Node right = node.right; int leftHeight = left != null ? left.height : 0; int rightHeight = right != null ? right.height : 0; int delta = leftHeight - rightHeight; if (delta == -2) { Node rightLeft = right.left; Node rightRight = right.right; int rightRightHeight = rightRight != null ? rightRight.height : 0; int rightLeftHeight = rightLeft != null ? rightLeft.height : 0; int rightDelta = rightLeftHeight - rightRightHeight; if (rightDelta == -1 || (rightDelta == 0 && !insert)) { rotateLeft(node); // AVL right right } else { assert (rightDelta == 1); rotateRight(right); // AVL right left rotateLeft(node); } if (insert) { break; // no further rotations will be necessary } } else if (delta == 2) { Node leftLeft = left.left; Node leftRight = left.right; int leftRightHeight = leftRight != null ? leftRight.height : 0; int leftLeftHeight = leftLeft != null ? leftLeft.height : 0; int leftDelta = leftLeftHeight - leftRightHeight; if (leftDelta == 1 || (leftDelta == 0 && !insert)) { rotateRight(node); // AVL left left } else { assert (leftDelta == -1); rotateLeft(left); // AVL left right rotateRight(node); } if (insert) { break; // no further rotations will be necessary } } else if (delta == 0) { node.height = leftHeight + 1; // leftHeight == rightHeight if (insert) { break; // the insert caused balance, so rebalancing is done! } } else { assert (delta == -1 || delta == 1); node.height = Math.max(leftHeight, rightHeight) + 1; if (!insert) { break; // the height hasn't changed, so rebalancing is done! } } } } /** * Rotates the subtree so that its root's right child is the new root. */ private void rotateLeft(Node root) { Node left = root.left; Node pivot = root.right; Node pivotLeft = pivot.left; Node pivotRight = pivot.right; // move the pivot's left child to the root's right root.right = pivotLeft; if (pivotLeft != null) { pivotLeft.parent = root; } replaceInParent(root, pivot); // move the root to the pivot's left pivot.left = root; root.parent = pivot; // fix heights root.height = Math.max(left != null ? left.height : 0, pivotLeft != null ? pivotLeft.height : 0) + 1; pivot.height = Math.max(root.height, pivotRight != null ? pivotRight.height : 0) + 1; } /** * Rotates the subtree so that its root's left child is the new root. */ private void rotateRight(Node root) { Node pivot = root.left; Node right = root.right; Node pivotLeft = pivot.left; Node pivotRight = pivot.right; // move the pivot's right child to the root's left root.left = pivotRight; if (pivotRight != null) { pivotRight.parent = root; } replaceInParent(root, pivot); // move the root to the pivot's right pivot.right = root; root.parent = pivot; // fixup heights root.height = Math.max(right != null ? right.height : 0, pivotRight != null ? pivotRight.height : 0) + 1; pivot.height = Math.max(root.height, pivotLeft != null ? pivotLeft.height : 0) + 1; } private EntrySet entrySet; private KeySet keySet; @Override public Set> entrySet() { EntrySet result = entrySet; return result != null ? result : (entrySet = new EntrySet()); } @Override public Set keySet() { KeySet result = keySet; return result != null ? result : (keySet = new KeySet()); } static final class Node implements Entry { Node parent; Node left; Node right; Node next; Node prev; final K key; final int hash; V value; int height; /** Create the header entry */ Node() { key = null; hash = -1; next = prev = this; } /** Create a regular entry */ Node(Node parent, K key, int hash, Node next, Node prev) { this.parent = parent; this.key = key; this.hash = hash; this.height = 1; this.next = next; this.prev = prev; prev.next = this; next.prev = this; } public K getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { V oldValue = this.value; this.value = value; return oldValue; } @SuppressWarnings("rawtypes") @Override public boolean equals(Object o) { if (o instanceof Entry) { Entry other = (Entry) o; return (key == null ? other.getKey() == null : key.equals(other.getKey())) && (value == null ? other.getValue() == null : value.equals(other.getValue())); } return false; } @Override public int hashCode() { return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } @Override public String toString() { return key + "=" + value; } /** * Returns the first node in this subtree. */ public Node first() { Node node = this; Node child = node.left; while (child != null) { node = child; child = node.left; } return node; } /** * Returns the last node in this subtree. */ public Node last() { Node node = this; Node child = node.right; while (child != null) { node = child; child = node.right; } return node; } } private void doubleCapacity() { table = doubleCapacity(table); threshold = (table.length / 2) + (table.length / 4); // 3/4 capacity } /** * Returns a new array containing the same nodes as {@code oldTable}, but with * twice as many trees, each of (approximately) half the previous size. */ static Node[] doubleCapacity(Node[] oldTable) { // TODO: don't do anything if we're already at MAX_CAPACITY int oldCapacity = oldTable.length; @SuppressWarnings("unchecked") // Arrays and generics don't get along. Node[] newTable = new Node[oldCapacity * 2]; AvlIterator iterator = new AvlIterator(); AvlBuilder leftBuilder = new AvlBuilder(); AvlBuilder rightBuilder = new AvlBuilder(); // Split each tree into two trees. for (int i = 0; i < oldCapacity; i++) { Node root = oldTable[i]; if (root == null) { continue; } // Compute the sizes of the left and right trees. iterator.reset(root); int leftSize = 0; int rightSize = 0; for (Node node; (node = iterator.next()) != null; ) { if ((node.hash & oldCapacity) == 0) { leftSize++; } else { rightSize++; } } // Split the tree into two. leftBuilder.reset(leftSize); rightBuilder.reset(rightSize); iterator.reset(root); for (Node node; (node = iterator.next()) != null; ) { if ((node.hash & oldCapacity) == 0) { leftBuilder.add(node); } else { rightBuilder.add(node); } } // Populate the enlarged array with these new roots. newTable[i] = leftSize > 0 ? leftBuilder.root() : null; newTable[i + oldCapacity] = rightSize > 0 ? rightBuilder.root() : null; } return newTable; } /** * Walks an AVL tree in iteration order. Once a node has been returned, its * left, right and parent links are no longer used. For this * reason it is safe to transform these links as you walk a tree. * *

Warning: this iterator is destructive. It clears the * parent node of all nodes in the tree. It is an error to make a partial * iteration of a tree. */ static class AvlIterator { /** This stack is a singly linked list, linked by the 'parent' field. */ private Node stackTop; void reset(Node root) { Node stackTop = null; for (Node n = root; n != null; n = n.left) { n.parent = stackTop; stackTop = n; // Stack push. } this.stackTop = stackTop; } public Node next() { Node stackTop = this.stackTop; if (stackTop == null) { return null; } Node result = stackTop; stackTop = result.parent; result.parent = null; for (Node n = result.right; n != null; n = n.left) { n.parent = stackTop; stackTop = n; // Stack push. } this.stackTop = stackTop; return result; } } /** * Builds AVL trees of a predetermined size by accepting nodes of increasing * value. To use: *

    *
  1. Call {@link #reset} to initialize the target size size. *
  2. Call {@link #add} size times with increasing values. *
  3. Call {@link #root} to get the root of the balanced tree. *
* *

The returned tree will satisfy the AVL constraint: for every node * N, the height of N.left and N.right is different by at * most 1. It accomplishes this by omitting deepest-level leaf nodes when * building trees whose size isn't a power of 2 minus 1. * *

Unlike rebuilding a tree from scratch, this approach requires no value * comparisons. Using this class to create a tree of size S is * {@code O(S)}. */ final static class AvlBuilder { /** This stack is a singly linked list, linked by the 'parent' field. */ private Node stack; private int leavesToSkip; private int leavesSkipped; private int size; void reset(int targetSize) { // compute the target tree size. This is a power of 2 minus one, like 15 or 31. int treeCapacity = Integer.highestOneBit(targetSize) * 2 - 1; leavesToSkip = treeCapacity - targetSize; size = 0; leavesSkipped = 0; stack = null; } void add(Node node) { node.left = node.parent = node.right = null; node.height = 1; // Skip a leaf if necessary. if (leavesToSkip > 0 && (size & 1) == 0) { size++; leavesToSkip--; leavesSkipped++; } node.parent = stack; stack = node; // Stack push. size++; // Skip a leaf if necessary. if (leavesToSkip > 0 && (size & 1) == 0) { size++; leavesToSkip--; leavesSkipped++; } /* * Combine 3 nodes into subtrees whenever the size is one less than a * multiple of 4. For example we combine the nodes A, B, C into a * 3-element tree with B as the root. * * Combine two subtrees and a spare single value whenever the size is one * less than a multiple of 8. For example at 8 we may combine subtrees * (A B C) and (E F G) with D as the root to form ((A B C) D (E F G)). * * Just as we combine single nodes when size nears a multiple of 4, and * 3-element trees when size nears a multiple of 8, we combine subtrees of * size (N-1) whenever the total size is 2N-1 whenever N is a power of 2. */ for (int scale = 4; (size & scale - 1) == scale - 1; scale *= 2) { if (leavesSkipped == 0) { // Pop right, center and left, then make center the top of the stack. Node right = stack; Node center = right.parent; Node left = center.parent; center.parent = left.parent; stack = center; // Construct a tree. center.left = left; center.right = right; center.height = right.height + 1; left.parent = center; right.parent = center; } else if (leavesSkipped == 1) { // Pop right and center, then make center the top of the stack. Node right = stack; Node center = right.parent; stack = center; // Construct a tree with no left child. center.right = right; center.height = right.height + 1; right.parent = center; leavesSkipped = 0; } else if (leavesSkipped == 2) { leavesSkipped = 0; } } } Node root() { Node stackTop = this.stack; if (stackTop.parent != null) { throw new IllegalStateException(); } return stackTop; } } private abstract class LinkedTreeMapIterator implements Iterator { Node next = header.next; Node lastReturned = null; int expectedModCount = modCount; LinkedTreeMapIterator() { } public final boolean hasNext() { return next != header; } final Node nextNode() { Node e = next; if (e == header) { throw new NoSuchElementException(); } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } next = e.next; return lastReturned = e; } public final void remove() { if (lastReturned == null) { throw new IllegalStateException(); } removeInternal(lastReturned, true); lastReturned = null; expectedModCount = modCount; } } final class EntrySet extends AbstractSet> { @Override public int size() { return size; } @Override public Iterator> iterator() { return new LinkedTreeMapIterator>() { public Entry next() { return nextNode(); } }; } @Override public boolean contains(Object o) { return o instanceof Entry && findByEntry((Entry) o) != null; } @Override public boolean remove(Object o) { if (!(o instanceof Entry)) { return false; } Node node = findByEntry((Entry) o); if (node == null) { return false; } removeInternal(node, true); return true; } @Override public void clear() { LinkedHashTreeMap.this.clear(); } } final class KeySet extends AbstractSet { @Override public int size() { return size; } @Override public Iterator iterator() { return new LinkedTreeMapIterator() { public K next() { return nextNode().key; } }; } @Override public boolean contains(Object o) { return containsKey(o); } @Override public boolean remove(Object key) { return removeInternalByKey(key) != null; } @Override public void clear() { LinkedHashTreeMap.this.clear(); } } /** * If somebody is unlucky enough to have to serialize one of these, serialize * it as a LinkedHashMap so that they won't need Gson on the other side to * deserialize it. Using serialization defeats our DoS defence, so most apps * shouldn't use it. */ private Object writeReplace() throws ObjectStreamException { return new LinkedHashMap(this); } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/internal/LinkedTreeMap.java000066400000000000000000000427431316034351600305050ustar00rootroot00000000000000/* * Copyright (C) 2010 The Android Open Source Project * Copyright (C) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.internal; import java.io.ObjectStreamException; import java.io.Serializable; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Comparator; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.NoSuchElementException; import java.util.Set; /** * A map of comparable keys to values. Unlike {@code TreeMap}, this class uses * insertion order for iteration order. Comparison order is only used as an * optimization for efficient insertion and removal. * *

This implementation was derived from Android 4.1's TreeMap class. */ public final class LinkedTreeMap extends AbstractMap implements Serializable { @SuppressWarnings({ "unchecked", "rawtypes" }) // to avoid Comparable>> private static final Comparator NATURAL_ORDER = new Comparator() { public int compare(Comparable a, Comparable b) { return a.compareTo(b); } }; Comparator comparator; Node root; int size = 0; int modCount = 0; // Used to preserve iteration order final Node header = new Node(); /** * Create a natural order, empty tree map whose keys must be mutually * comparable and non-null. */ @SuppressWarnings("unchecked") // unsafe! this assumes K is comparable public LinkedTreeMap() { this((Comparator) NATURAL_ORDER); } /** * Create a tree map ordered by {@code comparator}. This map's keys may only * be null if {@code comparator} permits. * * @param comparator the comparator to order elements with, or {@code null} to * use the natural ordering. */ @SuppressWarnings({ "unchecked", "rawtypes" }) // unsafe! if comparator is null, this assumes K is comparable public LinkedTreeMap(Comparator comparator) { this.comparator = comparator != null ? comparator : (Comparator) NATURAL_ORDER; } @Override public int size() { return size; } @Override public V get(Object key) { Node node = findByObject(key); return node != null ? node.value : null; } @Override public boolean containsKey(Object key) { return findByObject(key) != null; } @Override public V put(K key, V value) { if (key == null) { throw new NullPointerException("key == null"); } Node created = find(key, true); V result = created.value; created.value = value; return result; } @Override public void clear() { root = null; size = 0; modCount++; // Clear iteration order Node header = this.header; header.next = header.prev = header; } @Override public V remove(Object key) { Node node = removeInternalByKey(key); return node != null ? node.value : null; } /** * Returns the node at or adjacent to the given key, creating it if requested. * * @throws ClassCastException if {@code key} and the tree's keys aren't * mutually comparable. */ Node find(K key, boolean create) { Comparator comparator = this.comparator; Node nearest = root; int comparison = 0; if (nearest != null) { // Micro-optimization: avoid polymorphic calls to Comparator.compare(). @SuppressWarnings("unchecked") // Throws a ClassCastException below if there's trouble. Comparable comparableKey = (comparator == NATURAL_ORDER) ? (Comparable) key : null; while (true) { comparison = (comparableKey != null) ? comparableKey.compareTo(nearest.key) : comparator.compare(key, nearest.key); // We found the requested key. if (comparison == 0) { return nearest; } // If it exists, the key is in a subtree. Go deeper. Node child = (comparison < 0) ? nearest.left : nearest.right; if (child == null) { break; } nearest = child; } } // The key doesn't exist in this tree. if (!create) { return null; } // Create the node and add it to the tree or the table. Node header = this.header; Node created; if (nearest == null) { // Check that the value is comparable if we didn't do any comparisons. if (comparator == NATURAL_ORDER && !(key instanceof Comparable)) { throw new ClassCastException(key.getClass().getName() + " is not Comparable"); } created = new Node(nearest, key, header, header.prev); root = created; } else { created = new Node(nearest, key, header, header.prev); if (comparison < 0) { // nearest.key is higher nearest.left = created; } else { // comparison > 0, nearest.key is lower nearest.right = created; } rebalance(nearest, true); } size++; modCount++; return created; } @SuppressWarnings("unchecked") Node findByObject(Object key) { try { return key != null ? find((K) key, false) : null; } catch (ClassCastException e) { return null; } } /** * Returns this map's entry that has the same key and value as {@code * entry}, or null if this map has no such entry. * *

This method uses the comparator for key equality rather than {@code * equals}. If this map's comparator isn't consistent with equals (such as * {@code String.CASE_INSENSITIVE_ORDER}), then {@code remove()} and {@code * contains()} will violate the collections API. */ Node findByEntry(Entry entry) { Node mine = findByObject(entry.getKey()); boolean valuesEqual = mine != null && equal(mine.value, entry.getValue()); return valuesEqual ? mine : null; } private boolean equal(Object a, Object b) { return a == b || (a != null && a.equals(b)); } /** * Removes {@code node} from this tree, rearranging the tree's structure as * necessary. * * @param unlink true to also unlink this node from the iteration linked list. */ void removeInternal(Node node, boolean unlink) { if (unlink) { node.prev.next = node.next; node.next.prev = node.prev; } Node left = node.left; Node right = node.right; Node originalParent = node.parent; if (left != null && right != null) { /* * To remove a node with both left and right subtrees, move an * adjacent node from one of those subtrees into this node's place. * * Removing the adjacent node may change this node's subtrees. This * node may no longer have two subtrees once the adjacent node is * gone! */ Node adjacent = (left.height > right.height) ? left.last() : right.first(); removeInternal(adjacent, false); // takes care of rebalance and size-- int leftHeight = 0; left = node.left; if (left != null) { leftHeight = left.height; adjacent.left = left; left.parent = adjacent; node.left = null; } int rightHeight = 0; right = node.right; if (right != null) { rightHeight = right.height; adjacent.right = right; right.parent = adjacent; node.right = null; } adjacent.height = Math.max(leftHeight, rightHeight) + 1; replaceInParent(node, adjacent); return; } else if (left != null) { replaceInParent(node, left); node.left = null; } else if (right != null) { replaceInParent(node, right); node.right = null; } else { replaceInParent(node, null); } rebalance(originalParent, false); size--; modCount++; } Node removeInternalByKey(Object key) { Node node = findByObject(key); if (node != null) { removeInternal(node, true); } return node; } private void replaceInParent(Node node, Node replacement) { Node parent = node.parent; node.parent = null; if (replacement != null) { replacement.parent = parent; } if (parent != null) { if (parent.left == node) { parent.left = replacement; } else { assert (parent.right == node); parent.right = replacement; } } else { root = replacement; } } /** * Rebalances the tree by making any AVL rotations necessary between the * newly-unbalanced node and the tree's root. * * @param insert true if the node was unbalanced by an insert; false if it * was by a removal. */ private void rebalance(Node unbalanced, boolean insert) { for (Node node = unbalanced; node != null; node = node.parent) { Node left = node.left; Node right = node.right; int leftHeight = left != null ? left.height : 0; int rightHeight = right != null ? right.height : 0; int delta = leftHeight - rightHeight; if (delta == -2) { Node rightLeft = right.left; Node rightRight = right.right; int rightRightHeight = rightRight != null ? rightRight.height : 0; int rightLeftHeight = rightLeft != null ? rightLeft.height : 0; int rightDelta = rightLeftHeight - rightRightHeight; if (rightDelta == -1 || (rightDelta == 0 && !insert)) { rotateLeft(node); // AVL right right } else { assert (rightDelta == 1); rotateRight(right); // AVL right left rotateLeft(node); } if (insert) { break; // no further rotations will be necessary } } else if (delta == 2) { Node leftLeft = left.left; Node leftRight = left.right; int leftRightHeight = leftRight != null ? leftRight.height : 0; int leftLeftHeight = leftLeft != null ? leftLeft.height : 0; int leftDelta = leftLeftHeight - leftRightHeight; if (leftDelta == 1 || (leftDelta == 0 && !insert)) { rotateRight(node); // AVL left left } else { assert (leftDelta == -1); rotateLeft(left); // AVL left right rotateRight(node); } if (insert) { break; // no further rotations will be necessary } } else if (delta == 0) { node.height = leftHeight + 1; // leftHeight == rightHeight if (insert) { break; // the insert caused balance, so rebalancing is done! } } else { assert (delta == -1 || delta == 1); node.height = Math.max(leftHeight, rightHeight) + 1; if (!insert) { break; // the height hasn't changed, so rebalancing is done! } } } } /** * Rotates the subtree so that its root's right child is the new root. */ private void rotateLeft(Node root) { Node left = root.left; Node pivot = root.right; Node pivotLeft = pivot.left; Node pivotRight = pivot.right; // move the pivot's left child to the root's right root.right = pivotLeft; if (pivotLeft != null) { pivotLeft.parent = root; } replaceInParent(root, pivot); // move the root to the pivot's left pivot.left = root; root.parent = pivot; // fix heights root.height = Math.max(left != null ? left.height : 0, pivotLeft != null ? pivotLeft.height : 0) + 1; pivot.height = Math.max(root.height, pivotRight != null ? pivotRight.height : 0) + 1; } /** * Rotates the subtree so that its root's left child is the new root. */ private void rotateRight(Node root) { Node pivot = root.left; Node right = root.right; Node pivotLeft = pivot.left; Node pivotRight = pivot.right; // move the pivot's right child to the root's left root.left = pivotRight; if (pivotRight != null) { pivotRight.parent = root; } replaceInParent(root, pivot); // move the root to the pivot's right pivot.right = root; root.parent = pivot; // fixup heights root.height = Math.max(right != null ? right.height : 0, pivotRight != null ? pivotRight.height : 0) + 1; pivot.height = Math.max(root.height, pivotLeft != null ? pivotLeft.height : 0) + 1; } private EntrySet entrySet; private KeySet keySet; @Override public Set> entrySet() { EntrySet result = entrySet; return result != null ? result : (entrySet = new EntrySet()); } @Override public Set keySet() { KeySet result = keySet; return result != null ? result : (keySet = new KeySet()); } static final class Node implements Entry { Node parent; Node left; Node right; Node next; Node prev; final K key; V value; int height; /** Create the header entry */ Node() { key = null; next = prev = this; } /** Create a regular entry */ Node(Node parent, K key, Node next, Node prev) { this.parent = parent; this.key = key; this.height = 1; this.next = next; this.prev = prev; prev.next = this; next.prev = this; } public K getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { V oldValue = this.value; this.value = value; return oldValue; } @SuppressWarnings("rawtypes") @Override public boolean equals(Object o) { if (o instanceof Entry) { Entry other = (Entry) o; return (key == null ? other.getKey() == null : key.equals(other.getKey())) && (value == null ? other.getValue() == null : value.equals(other.getValue())); } return false; } @Override public int hashCode() { return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } @Override public String toString() { return key + "=" + value; } /** * Returns the first node in this subtree. */ public Node first() { Node node = this; Node child = node.left; while (child != null) { node = child; child = node.left; } return node; } /** * Returns the last node in this subtree. */ public Node last() { Node node = this; Node child = node.right; while (child != null) { node = child; child = node.right; } return node; } } private abstract class LinkedTreeMapIterator implements Iterator { Node next = header.next; Node lastReturned = null; int expectedModCount = modCount; LinkedTreeMapIterator() { } public final boolean hasNext() { return next != header; } final Node nextNode() { Node e = next; if (e == header) { throw new NoSuchElementException(); } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } next = e.next; return lastReturned = e; } public final void remove() { if (lastReturned == null) { throw new IllegalStateException(); } removeInternal(lastReturned, true); lastReturned = null; expectedModCount = modCount; } } class EntrySet extends AbstractSet> { @Override public int size() { return size; } @Override public Iterator> iterator() { return new LinkedTreeMapIterator>() { public Entry next() { return nextNode(); } }; } @Override public boolean contains(Object o) { return o instanceof Entry && findByEntry((Entry) o) != null; } @Override public boolean remove(Object o) { if (!(o instanceof Entry)) { return false; } Node node = findByEntry((Entry) o); if (node == null) { return false; } removeInternal(node, true); return true; } @Override public void clear() { LinkedTreeMap.this.clear(); } } final class KeySet extends AbstractSet { @Override public int size() { return size; } @Override public Iterator iterator() { return new LinkedTreeMapIterator() { public K next() { return nextNode().key; } }; } @Override public boolean contains(Object o) { return containsKey(o); } @Override public boolean remove(Object key) { return removeInternalByKey(key) != null; } @Override public void clear() { LinkedTreeMap.this.clear(); } } /** * If somebody is unlucky enough to have to serialize one of these, serialize * it as a LinkedHashMap so that they won't need Gson on the other side to * deserialize it. Using serialization defeats our DoS defence, so most apps * shouldn't use it. */ private Object writeReplace() throws ObjectStreamException { return new LinkedHashMap(this); } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/internal/ObjectConstructor.java000066400000000000000000000017731316034351600314730ustar00rootroot00000000000000/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.internal; /** * Defines a generic object construction factory. The purpose of this class * is to construct a default instance of a class that can be used for object * navigation while deserialization from its JSON representation. * * @author Inderjeet Singh * @author Joel Leitch */ public interface ObjectConstructor { /** * Returns a new instance. */ public T construct(); }gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/internal/Primitives.java000066400000000000000000000100711316034351600301410ustar00rootroot00000000000000/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.internal; import java.lang.reflect.Type; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * Contains static utility methods pertaining to primitive types and their * corresponding wrapper types. * * @author Kevin Bourrillion */ public final class Primitives { private Primitives() { throw new UnsupportedOperationException(); } /** A map from primitive types to their corresponding wrapper types. */ private static final Map, Class> PRIMITIVE_TO_WRAPPER_TYPE; /** A map from wrapper types to their corresponding primitive types. */ private static final Map, Class> WRAPPER_TO_PRIMITIVE_TYPE; // Sad that we can't use a BiMap. :( static { Map, Class> primToWrap = new HashMap, Class>(16); Map, Class> wrapToPrim = new HashMap, Class>(16); add(primToWrap, wrapToPrim, boolean.class, Boolean.class); add(primToWrap, wrapToPrim, byte.class, Byte.class); add(primToWrap, wrapToPrim, char.class, Character.class); add(primToWrap, wrapToPrim, double.class, Double.class); add(primToWrap, wrapToPrim, float.class, Float.class); add(primToWrap, wrapToPrim, int.class, Integer.class); add(primToWrap, wrapToPrim, long.class, Long.class); add(primToWrap, wrapToPrim, short.class, Short.class); add(primToWrap, wrapToPrim, void.class, Void.class); PRIMITIVE_TO_WRAPPER_TYPE = Collections.unmodifiableMap(primToWrap); WRAPPER_TO_PRIMITIVE_TYPE = Collections.unmodifiableMap(wrapToPrim); } private static void add(Map, Class> forward, Map, Class> backward, Class key, Class value) { forward.put(key, value); backward.put(value, key); } /** * Returns true if this type is a primitive. */ public static boolean isPrimitive(Type type) { return PRIMITIVE_TO_WRAPPER_TYPE.containsKey(type); } /** * Returns {@code true} if {@code type} is one of the nine * primitive-wrapper types, such as {@link Integer}. * * @see Class#isPrimitive */ public static boolean isWrapperType(Type type) { return WRAPPER_TO_PRIMITIVE_TYPE.containsKey( $Gson$Preconditions.checkNotNull(type)); } /** * Returns the corresponding wrapper type of {@code type} if it is a primitive * type; otherwise returns {@code type} itself. Idempotent. *

   *     wrap(int.class) == Integer.class
   *     wrap(Integer.class) == Integer.class
   *     wrap(String.class) == String.class
   * 
*/ public static Class wrap(Class type) { // cast is safe: long.class and Long.class are both of type Class @SuppressWarnings("unchecked") Class wrapped = (Class) PRIMITIVE_TO_WRAPPER_TYPE.get( $Gson$Preconditions.checkNotNull(type)); return (wrapped == null) ? type : wrapped; } /** * Returns the corresponding primitive type of {@code type} if it is a * wrapper type; otherwise returns {@code type} itself. Idempotent. *
   *     unwrap(Integer.class) == int.class
   *     unwrap(int.class) == int.class
   *     unwrap(String.class) == String.class
   * 
*/ public static Class unwrap(Class type) { // cast is safe: long.class and Long.class are both of type Class @SuppressWarnings("unchecked") Class unwrapped = (Class) WRAPPER_TO_PRIMITIVE_TYPE.get( $Gson$Preconditions.checkNotNull(type)); return (unwrapped == null) ? type : unwrapped; } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/internal/Streams.java000066400000000000000000000071601316034351600274310ustar00rootroot00000000000000/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.internal; import com.google.gson.JsonElement; import com.google.gson.JsonIOException; import com.google.gson.JsonNull; import com.google.gson.JsonParseException; import com.google.gson.JsonSyntaxException; import com.google.gson.internal.bind.TypeAdapters; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.google.gson.stream.MalformedJsonException; import java.io.EOFException; import java.io.IOException; import java.io.Writer; /** * Reads and writes GSON parse trees over streams. */ public final class Streams { private Streams() { throw new UnsupportedOperationException(); } /** * Takes a reader in any state and returns the next value as a JsonElement. */ public static JsonElement parse(JsonReader reader) throws JsonParseException { boolean isEmpty = true; try { reader.peek(); isEmpty = false; return TypeAdapters.JSON_ELEMENT.read(reader); } catch (EOFException e) { /* * For compatibility with JSON 1.5 and earlier, we return a JsonNull for * empty documents instead of throwing. */ if (isEmpty) { return JsonNull.INSTANCE; } // The stream ended prematurely so it is likely a syntax error. throw new JsonSyntaxException(e); } catch (MalformedJsonException e) { throw new JsonSyntaxException(e); } catch (IOException e) { throw new JsonIOException(e); } catch (NumberFormatException e) { throw new JsonSyntaxException(e); } } /** * Writes the JSON element to the writer, recursively. */ public static void write(JsonElement element, JsonWriter writer) throws IOException { TypeAdapters.JSON_ELEMENT.write(writer, element); } public static Writer writerForAppendable(Appendable appendable) { return appendable instanceof Writer ? (Writer) appendable : new AppendableWriter(appendable); } /** * Adapts an {@link Appendable} so it can be passed anywhere a {@link Writer} * is used. */ private static final class AppendableWriter extends Writer { private final Appendable appendable; private final CurrentWrite currentWrite = new CurrentWrite(); AppendableWriter(Appendable appendable) { this.appendable = appendable; } @Override public void write(char[] chars, int offset, int length) throws IOException { currentWrite.chars = chars; appendable.append(currentWrite, offset, offset + length); } @Override public void write(int i) throws IOException { appendable.append((char) i); } @Override public void flush() {} @Override public void close() {} /** * A mutable char sequence pointing at a single char[]. */ static class CurrentWrite implements CharSequence { char[] chars; public int length() { return chars.length; } public char charAt(int i) { return chars[i]; } public CharSequence subSequence(int start, int end) { return new String(chars, start, end - start); } } } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/internal/UnsafeAllocator.java000066400000000000000000000103701316034351600310720ustar00rootroot00000000000000/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.internal; import java.io.ObjectInputStream; import java.io.ObjectStreamClass; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; /** * Do sneaky things to allocate objects without invoking their constructors. * * @author Joel Leitch * @author Jesse Wilson */ public abstract class UnsafeAllocator { public abstract T newInstance(Class c) throws Exception; public static UnsafeAllocator create() { // try JVM // public class Unsafe { // public Object allocateInstance(Class type); // } try { Class unsafeClass = Class.forName("sun.misc.Unsafe"); Field f = unsafeClass.getDeclaredField("theUnsafe"); f.setAccessible(true); final Object unsafe = f.get(null); final Method allocateInstance = unsafeClass.getMethod("allocateInstance", Class.class); return new UnsafeAllocator() { @Override @SuppressWarnings("unchecked") public T newInstance(Class c) throws Exception { assertInstantiable(c); return (T) allocateInstance.invoke(unsafe, c); } }; } catch (Exception ignored) { } // try dalvikvm, post-gingerbread // public class ObjectStreamClass { // private static native int getConstructorId(Class c); // private static native Object newInstance(Class instantiationClass, int methodId); // } try { Method getConstructorId = ObjectStreamClass.class .getDeclaredMethod("getConstructorId", Class.class); getConstructorId.setAccessible(true); final int constructorId = (Integer) getConstructorId.invoke(null, Object.class); final Method newInstance = ObjectStreamClass.class .getDeclaredMethod("newInstance", Class.class, int.class); newInstance.setAccessible(true); return new UnsafeAllocator() { @Override @SuppressWarnings("unchecked") public T newInstance(Class c) throws Exception { assertInstantiable(c); return (T) newInstance.invoke(null, c, constructorId); } }; } catch (Exception ignored) { } // try dalvikvm, pre-gingerbread // public class ObjectInputStream { // private static native Object newInstance( // Class instantiationClass, Class constructorClass); // } try { final Method newInstance = ObjectInputStream.class .getDeclaredMethod("newInstance", Class.class, Class.class); newInstance.setAccessible(true); return new UnsafeAllocator() { @Override @SuppressWarnings("unchecked") public T newInstance(Class c) throws Exception { assertInstantiable(c); return (T) newInstance.invoke(null, c, Object.class); } }; } catch (Exception ignored) { } // give up return new UnsafeAllocator() { @Override public T newInstance(Class c) { throw new UnsupportedOperationException("Cannot allocate " + c); } }; } /** * Check if the class can be instantiated by unsafe allocator. If the instance has interface or abstract modifiers * throw an {@link java.lang.UnsupportedOperationException} * @param c instance of the class to be checked */ static void assertInstantiable(Class c) { int modifiers = c.getModifiers(); if (Modifier.isInterface(modifiers)) { throw new UnsupportedOperationException("Interface can't be instantiated! Interface name: " + c.getName()); } if (Modifier.isAbstract(modifiers)) { throw new UnsupportedOperationException("Abstract class can't be instantiated! Class name: " + c.getName()); } } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/internal/bind/000077500000000000000000000000001316034351600260605ustar00rootroot00000000000000gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/internal/bind/ArrayTypeAdapter.java000066400000000000000000000062271316034351600321530ustar00rootroot00000000000000/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.internal.bind; import java.io.IOException; import java.lang.reflect.Array; import java.lang.reflect.GenericArrayType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.internal.$Gson$Types; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; /** * Adapt an array of objects. */ public final class ArrayTypeAdapter extends TypeAdapter { public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() { @SuppressWarnings({"unchecked", "rawtypes"}) @Override public TypeAdapter create(Gson gson, TypeToken typeToken) { Type type = typeToken.getType(); if (!(type instanceof GenericArrayType || type instanceof Class && ((Class) type).isArray())) { return null; } Type componentType = $Gson$Types.getArrayComponentType(type); TypeAdapter componentTypeAdapter = gson.getAdapter(TypeToken.get(componentType)); return new ArrayTypeAdapter( gson, componentTypeAdapter, $Gson$Types.getRawType(componentType)); } }; private final Class componentType; private final TypeAdapter componentTypeAdapter; public ArrayTypeAdapter(Gson context, TypeAdapter componentTypeAdapter, Class componentType) { this.componentTypeAdapter = new TypeAdapterRuntimeTypeWrapper(context, componentTypeAdapter, componentType); this.componentType = componentType; } @Override public Object read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } List list = new ArrayList(); in.beginArray(); while (in.hasNext()) { E instance = componentTypeAdapter.read(in); list.add(instance); } in.endArray(); int size = list.size(); Object array = Array.newInstance(componentType, size); for (int i = 0; i < size; i++) { Array.set(array, i, list.get(i)); } return array; } @SuppressWarnings("unchecked") @Override public void write(JsonWriter out, Object array) throws IOException { if (array == null) { out.nullValue(); return; } out.beginArray(); for (int i = 0, length = Array.getLength(array); i < length; i++) { E value = (E) Array.get(array, i); componentTypeAdapter.write(out, value); } out.endArray(); } } CollectionTypeAdapterFactory.java000066400000000000000000000066521316034351600344430ustar00rootroot00000000000000gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/internal/bind/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.internal.bind; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.internal.$Gson$Types; import com.google.gson.internal.ConstructorConstructor; import com.google.gson.internal.ObjectConstructor; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.lang.reflect.Type; import java.util.Collection; /** * Adapt a homogeneous collection of objects. */ public final class CollectionTypeAdapterFactory implements TypeAdapterFactory { private final ConstructorConstructor constructorConstructor; public CollectionTypeAdapterFactory(ConstructorConstructor constructorConstructor) { this.constructorConstructor = constructorConstructor; } @Override public TypeAdapter create(Gson gson, TypeToken typeToken) { Type type = typeToken.getType(); Class rawType = typeToken.getRawType(); if (!Collection.class.isAssignableFrom(rawType)) { return null; } Type elementType = $Gson$Types.getCollectionElementType(type, rawType); TypeAdapter elementTypeAdapter = gson.getAdapter(TypeToken.get(elementType)); ObjectConstructor constructor = constructorConstructor.get(typeToken); @SuppressWarnings({"unchecked", "rawtypes"}) // create() doesn't define a type parameter TypeAdapter result = new Adapter(gson, elementType, elementTypeAdapter, constructor); return result; } private static final class Adapter extends TypeAdapter> { private final TypeAdapter elementTypeAdapter; private final ObjectConstructor> constructor; public Adapter(Gson context, Type elementType, TypeAdapter elementTypeAdapter, ObjectConstructor> constructor) { this.elementTypeAdapter = new TypeAdapterRuntimeTypeWrapper(context, elementTypeAdapter, elementType); this.constructor = constructor; } @Override public Collection read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } Collection collection = constructor.construct(); in.beginArray(); while (in.hasNext()) { E instance = elementTypeAdapter.read(in); collection.add(instance); } in.endArray(); return collection; } @Override public void write(JsonWriter out, Collection collection) throws IOException { if (collection == null) { out.nullValue(); return; } out.beginArray(); for (E element : collection) { elementTypeAdapter.write(out, element); } out.endArray(); } } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/internal/bind/DateTypeAdapter.java000066400000000000000000000057021316034351600317470ustar00rootroot00000000000000/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.internal.bind; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.internal.bind.util.ISO8601Utils; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.text.DateFormat; import java.text.ParseException; import java.text.ParsePosition; import java.util.Date; import java.util.Locale; /** * Adapter for Date. Although this class appears stateless, it is not. * DateFormat captures its time zone and locale when it is created, which gives * this class state. DateFormat isn't thread safe either, so this class has * to synchronize its read and write methods. */ public final class DateTypeAdapter extends TypeAdapter { public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() { @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal @Override public TypeAdapter create(Gson gson, TypeToken typeToken) { return typeToken.getRawType() == Date.class ? (TypeAdapter) new DateTypeAdapter() : null; } }; private final DateFormat enUsFormat = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.US); private final DateFormat localFormat = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT); @Override public Date read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } return deserializeToDate(in.nextString()); } private synchronized Date deserializeToDate(String json) { try { return localFormat.parse(json); } catch (ParseException ignored) { } try { return enUsFormat.parse(json); } catch (ParseException ignored) { } try { return ISO8601Utils.parse(json, new ParsePosition(0)); } catch (ParseException e) { throw new JsonSyntaxException(json, e); } } @Override public synchronized void write(JsonWriter out, Date value) throws IOException { if (value == null) { out.nullValue(); return; } String dateFormatAsString = enUsFormat.format(value); out.value(dateFormatAsString); } } JsonAdapterAnnotationTypeAdapterFactory.java000066400000000000000000000064061316034351600366120ustar00rootroot00000000000000gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/internal/bind/* * Copyright (C) 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.internal.bind; import com.google.gson.Gson; import com.google.gson.JsonDeserializer; import com.google.gson.JsonSerializer; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.annotations.JsonAdapter; import com.google.gson.internal.ConstructorConstructor; import com.google.gson.reflect.TypeToken; /** * Given a type T, looks for the annotation {@link JsonAdapter} and uses an instance of the * specified class as the default type adapter. * * @since 2.3 */ public final class JsonAdapterAnnotationTypeAdapterFactory implements TypeAdapterFactory { private final ConstructorConstructor constructorConstructor; public JsonAdapterAnnotationTypeAdapterFactory(ConstructorConstructor constructorConstructor) { this.constructorConstructor = constructorConstructor; } @SuppressWarnings("unchecked") @Override public TypeAdapter create(Gson gson, TypeToken targetType) { Class rawType = targetType.getRawType(); JsonAdapter annotation = rawType.getAnnotation(JsonAdapter.class); if (annotation == null) { return null; } return (TypeAdapter) getTypeAdapter(constructorConstructor, gson, targetType, annotation); } @SuppressWarnings({ "unchecked", "rawtypes" }) // Casts guarded by conditionals. TypeAdapter getTypeAdapter(ConstructorConstructor constructorConstructor, Gson gson, TypeToken type, JsonAdapter annotation) { Object instance = constructorConstructor.get(TypeToken.get(annotation.value())).construct(); TypeAdapter typeAdapter; if (instance instanceof TypeAdapter) { typeAdapter = (TypeAdapter) instance; } else if (instance instanceof TypeAdapterFactory) { typeAdapter = ((TypeAdapterFactory) instance).create(gson, type); } else if (instance instanceof JsonSerializer || instance instanceof JsonDeserializer) { JsonSerializer serializer = instance instanceof JsonSerializer ? (JsonSerializer) instance : null; JsonDeserializer deserializer = instance instanceof JsonDeserializer ? (JsonDeserializer) instance : null; typeAdapter = new TreeTypeAdapter(serializer, deserializer, gson, type, null); } else { throw new IllegalArgumentException("Invalid attempt to bind an instance of " + instance.getClass().getName() + " as a @JsonAdapter for " + type.toString() + ". @JsonAdapter value must be a TypeAdapter, TypeAdapterFactory," + " JsonSerializer or JsonDeserializer."); } if (typeAdapter != null && annotation.nullSafe()) { typeAdapter = typeAdapter.nullSafe(); } return typeAdapter; } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/internal/bind/JsonTreeReader.java000066400000000000000000000232141316034351600316010ustar00rootroot00000000000000/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.internal.bind; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonNull; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import java.io.IOException; import java.io.Reader; import java.util.Iterator; import java.util.Map; /** * This reader walks the elements of a JsonElement as if it was coming from a * character stream. * * @author Jesse Wilson */ public final class JsonTreeReader extends JsonReader { private static final Reader UNREADABLE_READER = new Reader() { @Override public int read(char[] buffer, int offset, int count) throws IOException { throw new AssertionError(); } @Override public void close() throws IOException { throw new AssertionError(); } }; private static final Object SENTINEL_CLOSED = new Object(); /* * The nesting stack. Using a manual array rather than an ArrayList saves 20%. */ private Object[] stack = new Object[32]; private int stackSize = 0; /* * The path members. It corresponds directly to stack: At indices where the * stack contains an object (EMPTY_OBJECT, DANGLING_NAME or NONEMPTY_OBJECT), * pathNames contains the name at this scope. Where it contains an array * (EMPTY_ARRAY, NONEMPTY_ARRAY) pathIndices contains the current index in * that array. Otherwise the value is undefined, and we take advantage of that * by incrementing pathIndices when doing so isn't useful. */ private String[] pathNames = new String[32]; private int[] pathIndices = new int[32]; public JsonTreeReader(JsonElement element) { super(UNREADABLE_READER); push(element); } @Override public void beginArray() throws IOException { expect(JsonToken.BEGIN_ARRAY); JsonArray array = (JsonArray) peekStack(); push(array.iterator()); pathIndices[stackSize - 1] = 0; } @Override public void endArray() throws IOException { expect(JsonToken.END_ARRAY); popStack(); // empty iterator popStack(); // array if (stackSize > 0) { pathIndices[stackSize - 1]++; } } @Override public void beginObject() throws IOException { expect(JsonToken.BEGIN_OBJECT); JsonObject object = (JsonObject) peekStack(); push(object.entrySet().iterator()); } @Override public void endObject() throws IOException { expect(JsonToken.END_OBJECT); popStack(); // empty iterator popStack(); // object if (stackSize > 0) { pathIndices[stackSize - 1]++; } } @Override public boolean hasNext() throws IOException { JsonToken token = peek(); return token != JsonToken.END_OBJECT && token != JsonToken.END_ARRAY; } @Override public JsonToken peek() throws IOException { if (stackSize == 0) { return JsonToken.END_DOCUMENT; } Object o = peekStack(); if (o instanceof Iterator) { boolean isObject = stack[stackSize - 2] instanceof JsonObject; Iterator iterator = (Iterator) o; if (iterator.hasNext()) { if (isObject) { return JsonToken.NAME; } else { push(iterator.next()); return peek(); } } else { return isObject ? JsonToken.END_OBJECT : JsonToken.END_ARRAY; } } else if (o instanceof JsonObject) { return JsonToken.BEGIN_OBJECT; } else if (o instanceof JsonArray) { return JsonToken.BEGIN_ARRAY; } else if (o instanceof JsonPrimitive) { JsonPrimitive primitive = (JsonPrimitive) o; if (primitive.isString()) { return JsonToken.STRING; } else if (primitive.isBoolean()) { return JsonToken.BOOLEAN; } else if (primitive.isNumber()) { return JsonToken.NUMBER; } else { throw new AssertionError(); } } else if (o instanceof JsonNull) { return JsonToken.NULL; } else if (o == SENTINEL_CLOSED) { throw new IllegalStateException("JsonReader is closed"); } else { throw new AssertionError(); } } private Object peekStack() { return stack[stackSize - 1]; } private Object popStack() { Object result = stack[--stackSize]; stack[stackSize] = null; return result; } private void expect(JsonToken expected) throws IOException { if (peek() != expected) { throw new IllegalStateException( "Expected " + expected + " but was " + peek() + locationString()); } } @Override public String nextName() throws IOException { expect(JsonToken.NAME); Iterator i = (Iterator) peekStack(); Map.Entry entry = (Map.Entry) i.next(); String result = (String) entry.getKey(); pathNames[stackSize - 1] = result; push(entry.getValue()); return result; } @Override public String nextString() throws IOException { JsonToken token = peek(); if (token != JsonToken.STRING && token != JsonToken.NUMBER) { throw new IllegalStateException( "Expected " + JsonToken.STRING + " but was " + token + locationString()); } String result = ((JsonPrimitive) popStack()).getAsString(); if (stackSize > 0) { pathIndices[stackSize - 1]++; } return result; } @Override public boolean nextBoolean() throws IOException { expect(JsonToken.BOOLEAN); boolean result = ((JsonPrimitive) popStack()).getAsBoolean(); if (stackSize > 0) { pathIndices[stackSize - 1]++; } return result; } @Override public void nextNull() throws IOException { expect(JsonToken.NULL); popStack(); if (stackSize > 0) { pathIndices[stackSize - 1]++; } } @Override public double nextDouble() throws IOException { JsonToken token = peek(); if (token != JsonToken.NUMBER && token != JsonToken.STRING) { throw new IllegalStateException( "Expected " + JsonToken.NUMBER + " but was " + token + locationString()); } double result = ((JsonPrimitive) peekStack()).getAsDouble(); if (!isLenient() && (Double.isNaN(result) || Double.isInfinite(result))) { throw new NumberFormatException("JSON forbids NaN and infinities: " + result); } popStack(); if (stackSize > 0) { pathIndices[stackSize - 1]++; } return result; } @Override public long nextLong() throws IOException { JsonToken token = peek(); if (token != JsonToken.NUMBER && token != JsonToken.STRING) { throw new IllegalStateException( "Expected " + JsonToken.NUMBER + " but was " + token + locationString()); } long result = ((JsonPrimitive) peekStack()).getAsLong(); popStack(); if (stackSize > 0) { pathIndices[stackSize - 1]++; } return result; } @Override public int nextInt() throws IOException { JsonToken token = peek(); if (token != JsonToken.NUMBER && token != JsonToken.STRING) { throw new IllegalStateException( "Expected " + JsonToken.NUMBER + " but was " + token + locationString()); } int result = ((JsonPrimitive) peekStack()).getAsInt(); popStack(); if (stackSize > 0) { pathIndices[stackSize - 1]++; } return result; } @Override public void close() throws IOException { stack = new Object[] { SENTINEL_CLOSED }; stackSize = 1; } @Override public void skipValue() throws IOException { if (peek() == JsonToken.NAME) { nextName(); pathNames[stackSize - 2] = "null"; } else { popStack(); if (stackSize > 0) { pathNames[stackSize - 1] = "null"; } } if (stackSize > 0) { pathIndices[stackSize - 1]++; } } @Override public String toString() { return getClass().getSimpleName(); } public void promoteNameToValue() throws IOException { expect(JsonToken.NAME); Iterator i = (Iterator) peekStack(); Map.Entry entry = (Map.Entry) i.next(); push(entry.getValue()); push(new JsonPrimitive((String) entry.getKey())); } private void push(Object newTop) { if (stackSize == stack.length) { Object[] newStack = new Object[stackSize * 2]; int[] newPathIndices = new int[stackSize * 2]; String[] newPathNames = new String[stackSize * 2]; System.arraycopy(stack, 0, newStack, 0, stackSize); System.arraycopy(pathIndices, 0, newPathIndices, 0, stackSize); System.arraycopy(pathNames, 0, newPathNames, 0, stackSize); stack = newStack; pathIndices = newPathIndices; pathNames = newPathNames; } stack[stackSize++] = newTop; } @Override public String getPath() { StringBuilder result = new StringBuilder().append('$'); for (int i = 0; i < stackSize; i++) { if (stack[i] instanceof JsonArray) { if (stack[++i] instanceof Iterator) { result.append('[').append(pathIndices[i]).append(']'); } } else if (stack[i] instanceof JsonObject) { if (stack[++i] instanceof Iterator) { result.append('.'); if (pathNames[i] != null) { result.append(pathNames[i]); } } } } return result.toString(); } private String locationString() { return " at path " + getPath(); } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/internal/bind/JsonTreeWriter.java000066400000000000000000000135361316034351600316610ustar00rootroot00000000000000/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.internal.bind; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonNull; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.List; /** * This writer creates a JsonElement. */ public final class JsonTreeWriter extends JsonWriter { private static final Writer UNWRITABLE_WRITER = new Writer() { @Override public void write(char[] buffer, int offset, int counter) { throw new AssertionError(); } @Override public void flush() throws IOException { throw new AssertionError(); } @Override public void close() throws IOException { throw new AssertionError(); } }; /** Added to the top of the stack when this writer is closed to cause following ops to fail. */ private static final JsonPrimitive SENTINEL_CLOSED = new JsonPrimitive("closed"); /** The JsonElements and JsonArrays under modification, outermost to innermost. */ private final List stack = new ArrayList(); /** The name for the next JSON object value. If non-null, the top of the stack is a JsonObject. */ private String pendingName; /** the JSON element constructed by this writer. */ private JsonElement product = JsonNull.INSTANCE; // TODO: is this really what we want?; public JsonTreeWriter() { super(UNWRITABLE_WRITER); } /** * Returns the top level object produced by this writer. */ public JsonElement get() { if (!stack.isEmpty()) { throw new IllegalStateException("Expected one JSON element but was " + stack); } return product; } private JsonElement peek() { return stack.get(stack.size() - 1); } private void put(JsonElement value) { if (pendingName != null) { if (!value.isJsonNull() || getSerializeNulls()) { JsonObject object = (JsonObject) peek(); object.add(pendingName, value); } pendingName = null; } else if (stack.isEmpty()) { product = value; } else { JsonElement element = peek(); if (element instanceof JsonArray) { ((JsonArray) element).add(value); } else { throw new IllegalStateException(); } } } @Override public JsonWriter beginArray() throws IOException { JsonArray array = new JsonArray(); put(array); stack.add(array); return this; } @Override public JsonWriter endArray() throws IOException { if (stack.isEmpty() || pendingName != null) { throw new IllegalStateException(); } JsonElement element = peek(); if (element instanceof JsonArray) { stack.remove(stack.size() - 1); return this; } throw new IllegalStateException(); } @Override public JsonWriter beginObject() throws IOException { JsonObject object = new JsonObject(); put(object); stack.add(object); return this; } @Override public JsonWriter endObject() throws IOException { if (stack.isEmpty() || pendingName != null) { throw new IllegalStateException(); } JsonElement element = peek(); if (element instanceof JsonObject) { stack.remove(stack.size() - 1); return this; } throw new IllegalStateException(); } @Override public JsonWriter name(String name) throws IOException { if (stack.isEmpty() || pendingName != null) { throw new IllegalStateException(); } JsonElement element = peek(); if (element instanceof JsonObject) { pendingName = name; return this; } throw new IllegalStateException(); } @Override public JsonWriter value(String value) throws IOException { if (value == null) { return nullValue(); } put(new JsonPrimitive(value)); return this; } @Override public JsonWriter nullValue() throws IOException { put(JsonNull.INSTANCE); return this; } @Override public JsonWriter value(boolean value) throws IOException { put(new JsonPrimitive(value)); return this; } @Override public JsonWriter value(Boolean value) throws IOException { if (value == null) { return nullValue(); } put(new JsonPrimitive(value)); return this; } @Override public JsonWriter value(double value) throws IOException { if (!isLenient() && (Double.isNaN(value) || Double.isInfinite(value))) { throw new IllegalArgumentException("JSON forbids NaN and infinities: " + value); } put(new JsonPrimitive(value)); return this; } @Override public JsonWriter value(long value) throws IOException { put(new JsonPrimitive(value)); return this; } @Override public JsonWriter value(Number value) throws IOException { if (value == null) { return nullValue(); } if (!isLenient()) { double d = value.doubleValue(); if (Double.isNaN(d) || Double.isInfinite(d)) { throw new IllegalArgumentException("JSON forbids NaN and infinities: " + value); } } put(new JsonPrimitive(value)); return this; } @Override public void flush() throws IOException { } @Override public void close() throws IOException { if (!stack.isEmpty()) { throw new IOException("Incomplete document"); } stack.add(SENTINEL_CLOSED); } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/internal/bind/MapTypeAdapterFactory.java000066400000000000000000000224661316034351600331450ustar00rootroot00000000000000/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.internal.bind; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSyntaxException; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.internal.$Gson$Types; import com.google.gson.internal.ConstructorConstructor; import com.google.gson.internal.JsonReaderInternalAccess; import com.google.gson.internal.ObjectConstructor; import com.google.gson.internal.Streams; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Adapts maps to either JSON objects or JSON arrays. * *

Maps as JSON objects

* For primitive keys or when complex map key serialization is not enabled, this * converts Java {@link Map Maps} to JSON Objects. This requires that map keys * can be serialized as strings; this is insufficient for some key types. For * example, consider a map whose keys are points on a grid. The default JSON * form encodes reasonably:
   {@code
 *   Map original = new LinkedHashMap();
 *   original.put(new Point(5, 6), "a");
 *   original.put(new Point(8, 8), "b");
 *   System.out.println(gson.toJson(original, type));
 * }
* The above code prints this JSON object:
   {@code
 *   {
 *     "(5,6)": "a",
 *     "(8,8)": "b"
 *   }
 * }
* But GSON is unable to deserialize this value because the JSON string name is * just the {@link Object#toString() toString()} of the map key. Attempting to * convert the above JSON to an object fails with a parse exception: *
com.google.gson.JsonParseException: Expecting object found: "(5,6)"
 *   at com.google.gson.JsonObjectDeserializationVisitor.visitFieldUsingCustomHandler
 *   at com.google.gson.ObjectNavigator.navigateClassFields
 *   ...
* *

Maps as JSON arrays

* An alternative approach taken by this type adapter when it is required and * complex map key serialization is enabled is to encode maps as arrays of map * entries. Each map entry is a two element array containing a key and a value. * This approach is more flexible because any type can be used as the map's key; * not just strings. But it's also less portable because the receiver of such * JSON must be aware of the map entry convention. * *

Register this adapter when you are creating your GSON instance. *

   {@code
 *   Gson gson = new GsonBuilder()
 *     .registerTypeAdapter(Map.class, new MapAsArrayTypeAdapter())
 *     .create();
 * }
* This will change the structure of the JSON emitted by the code above. Now we * get an array. In this case the arrays elements are map entries: *
   {@code
 *   [
 *     [
 *       {
 *         "x": 5,
 *         "y": 6
 *       },
 *       "a",
 *     ],
 *     [
 *       {
 *         "x": 8,
 *         "y": 8
 *       },
 *       "b"
 *     ]
 *   ]
 * }
* This format will serialize and deserialize just fine as long as this adapter * is registered. */ public final class MapTypeAdapterFactory implements TypeAdapterFactory { private final ConstructorConstructor constructorConstructor; final boolean complexMapKeySerialization; public MapTypeAdapterFactory(ConstructorConstructor constructorConstructor, boolean complexMapKeySerialization) { this.constructorConstructor = constructorConstructor; this.complexMapKeySerialization = complexMapKeySerialization; } @Override public TypeAdapter create(Gson gson, TypeToken typeToken) { Type type = typeToken.getType(); Class rawType = typeToken.getRawType(); if (!Map.class.isAssignableFrom(rawType)) { return null; } Class rawTypeOfSrc = $Gson$Types.getRawType(type); Type[] keyAndValueTypes = $Gson$Types.getMapKeyAndValueTypes(type, rawTypeOfSrc); TypeAdapter keyAdapter = getKeyAdapter(gson, keyAndValueTypes[0]); TypeAdapter valueAdapter = gson.getAdapter(TypeToken.get(keyAndValueTypes[1])); ObjectConstructor constructor = constructorConstructor.get(typeToken); @SuppressWarnings({"unchecked", "rawtypes"}) // we don't define a type parameter for the key or value types TypeAdapter result = new Adapter(gson, keyAndValueTypes[0], keyAdapter, keyAndValueTypes[1], valueAdapter, constructor); return result; } /** * Returns a type adapter that writes the value as a string. */ private TypeAdapter getKeyAdapter(Gson context, Type keyType) { return (keyType == boolean.class || keyType == Boolean.class) ? TypeAdapters.BOOLEAN_AS_STRING : context.getAdapter(TypeToken.get(keyType)); } private final class Adapter extends TypeAdapter> { private final TypeAdapter keyTypeAdapter; private final TypeAdapter valueTypeAdapter; private final ObjectConstructor> constructor; public Adapter(Gson context, Type keyType, TypeAdapter keyTypeAdapter, Type valueType, TypeAdapter valueTypeAdapter, ObjectConstructor> constructor) { this.keyTypeAdapter = new TypeAdapterRuntimeTypeWrapper(context, keyTypeAdapter, keyType); this.valueTypeAdapter = new TypeAdapterRuntimeTypeWrapper(context, valueTypeAdapter, valueType); this.constructor = constructor; } @Override public Map read(JsonReader in) throws IOException { JsonToken peek = in.peek(); if (peek == JsonToken.NULL) { in.nextNull(); return null; } Map map = constructor.construct(); if (peek == JsonToken.BEGIN_ARRAY) { in.beginArray(); while (in.hasNext()) { in.beginArray(); // entry array K key = keyTypeAdapter.read(in); V value = valueTypeAdapter.read(in); V replaced = map.put(key, value); if (replaced != null) { throw new JsonSyntaxException("duplicate key: " + key); } in.endArray(); } in.endArray(); } else { in.beginObject(); while (in.hasNext()) { JsonReaderInternalAccess.INSTANCE.promoteNameToValue(in); K key = keyTypeAdapter.read(in); V value = valueTypeAdapter.read(in); V replaced = map.put(key, value); if (replaced != null) { throw new JsonSyntaxException("duplicate key: " + key); } } in.endObject(); } return map; } @Override public void write(JsonWriter out, Map map) throws IOException { if (map == null) { out.nullValue(); return; } if (!complexMapKeySerialization) { out.beginObject(); for (Map.Entry entry : map.entrySet()) { out.name(String.valueOf(entry.getKey())); valueTypeAdapter.write(out, entry.getValue()); } out.endObject(); return; } boolean hasComplexKeys = false; List keys = new ArrayList(map.size()); List values = new ArrayList(map.size()); for (Map.Entry entry : map.entrySet()) { JsonElement keyElement = keyTypeAdapter.toJsonTree(entry.getKey()); keys.add(keyElement); values.add(entry.getValue()); hasComplexKeys |= keyElement.isJsonArray() || keyElement.isJsonObject(); } if (hasComplexKeys) { out.beginArray(); for (int i = 0, size = keys.size(); i < size; i++) { out.beginArray(); // entry array Streams.write(keys.get(i), out); valueTypeAdapter.write(out, values.get(i)); out.endArray(); } out.endArray(); } else { out.beginObject(); for (int i = 0, size = keys.size(); i < size; i++) { JsonElement keyElement = keys.get(i); out.name(keyToString(keyElement)); valueTypeAdapter.write(out, values.get(i)); } out.endObject(); } } private String keyToString(JsonElement keyElement) { if (keyElement.isJsonPrimitive()) { JsonPrimitive primitive = keyElement.getAsJsonPrimitive(); if (primitive.isNumber()) { return String.valueOf(primitive.getAsNumber()); } else if (primitive.isBoolean()) { return Boolean.toString(primitive.getAsBoolean()); } else if (primitive.isString()) { return primitive.getAsString(); } else { throw new AssertionError(); } } else if (keyElement.isJsonNull()) { return "null"; } else { throw new AssertionError(); } } } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/internal/bind/ObjectTypeAdapter.java000066400000000000000000000056271316034351600323060ustar00rootroot00000000000000/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.internal.bind; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.internal.LinkedTreeMap; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Adapts types whose static type is only 'Object'. Uses getClass() on * serialization and a primitive/Map/List on deserialization. */ public final class ObjectTypeAdapter extends TypeAdapter { public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() { @SuppressWarnings("unchecked") @Override public TypeAdapter create(Gson gson, TypeToken type) { if (type.getRawType() == Object.class) { return (TypeAdapter) new ObjectTypeAdapter(gson); } return null; } }; private final Gson gson; ObjectTypeAdapter(Gson gson) { this.gson = gson; } @Override public Object read(JsonReader in) throws IOException { JsonToken token = in.peek(); switch (token) { case BEGIN_ARRAY: List list = new ArrayList(); in.beginArray(); while (in.hasNext()) { list.add(read(in)); } in.endArray(); return list; case BEGIN_OBJECT: Map map = new LinkedTreeMap(); in.beginObject(); while (in.hasNext()) { map.put(in.nextName(), read(in)); } in.endObject(); return map; case STRING: return in.nextString(); case NUMBER: return in.nextDouble(); case BOOLEAN: return in.nextBoolean(); case NULL: in.nextNull(); return null; default: throw new IllegalStateException(); } } @SuppressWarnings("unchecked") @Override public void write(JsonWriter out, Object value) throws IOException { if (value == null) { out.nullValue(); return; } TypeAdapter typeAdapter = (TypeAdapter) gson.getAdapter(value.getClass()); if (typeAdapter instanceof ObjectTypeAdapter) { out.beginObject(); out.endObject(); return; } typeAdapter.write(out, value); } } ReflectiveTypeAdapterFactory.java000066400000000000000000000223441316034351600344340ustar00rootroot00000000000000gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/internal/bind/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.internal.bind; import com.google.gson.FieldNamingStrategy; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.internal.$Gson$Types; import com.google.gson.internal.ConstructorConstructor; import com.google.gson.internal.Excluder; import com.google.gson.internal.ObjectConstructor; import com.google.gson.internal.Primitives; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Type adapter that reflects over the fields and methods of a class. */ public final class ReflectiveTypeAdapterFactory implements TypeAdapterFactory { private final ConstructorConstructor constructorConstructor; private final FieldNamingStrategy fieldNamingPolicy; private final Excluder excluder; private final JsonAdapterAnnotationTypeAdapterFactory jsonAdapterFactory; public ReflectiveTypeAdapterFactory(ConstructorConstructor constructorConstructor, FieldNamingStrategy fieldNamingPolicy, Excluder excluder, JsonAdapterAnnotationTypeAdapterFactory jsonAdapterFactory) { this.constructorConstructor = constructorConstructor; this.fieldNamingPolicy = fieldNamingPolicy; this.excluder = excluder; this.jsonAdapterFactory = jsonAdapterFactory; } public boolean excludeField(Field f, boolean serialize) { return excludeField(f, serialize, excluder); } static boolean excludeField(Field f, boolean serialize, Excluder excluder) { return !excluder.excludeClass(f.getType(), serialize) && !excluder.excludeField(f, serialize); } /** first element holds the default name */ private List getFieldNames(Field f) { SerializedName annotation = f.getAnnotation(SerializedName.class); if (annotation == null) { String name = fieldNamingPolicy.translateName(f); return Collections.singletonList(name); } String serializedName = annotation.value(); String[] alternates = annotation.alternate(); if (alternates.length == 0) { return Collections.singletonList(serializedName); } List fieldNames = new ArrayList(alternates.length + 1); fieldNames.add(serializedName); for (String alternate : alternates) { fieldNames.add(alternate); } return fieldNames; } @Override public TypeAdapter create(Gson gson, final TypeToken type) { Class raw = type.getRawType(); if (!Object.class.isAssignableFrom(raw)) { return null; // it's a primitive! } ObjectConstructor constructor = constructorConstructor.get(type); return new Adapter(constructor, getBoundFields(gson, type, raw)); } private ReflectiveTypeAdapterFactory.BoundField createBoundField( final Gson context, final Field field, final String name, final TypeToken fieldType, boolean serialize, boolean deserialize) { final boolean isPrimitive = Primitives.isPrimitive(fieldType.getRawType()); // special casing primitives here saves ~5% on Android... JsonAdapter annotation = field.getAnnotation(JsonAdapter.class); TypeAdapter mapped = null; if (annotation != null) { mapped = jsonAdapterFactory.getTypeAdapter( constructorConstructor, context, fieldType, annotation); } final boolean jsonAdapterPresent = mapped != null; if (mapped == null) mapped = context.getAdapter(fieldType); final TypeAdapter typeAdapter = mapped; return new ReflectiveTypeAdapterFactory.BoundField(name, serialize, deserialize) { @SuppressWarnings({"unchecked", "rawtypes"}) // the type adapter and field type always agree @Override void write(JsonWriter writer, Object value) throws IOException, IllegalAccessException { Object fieldValue = field.get(value); TypeAdapter t = jsonAdapterPresent ? typeAdapter : new TypeAdapterRuntimeTypeWrapper(context, typeAdapter, fieldType.getType()); t.write(writer, fieldValue); } @Override void read(JsonReader reader, Object value) throws IOException, IllegalAccessException { Object fieldValue = typeAdapter.read(reader); if (fieldValue != null || !isPrimitive) { field.set(value, fieldValue); } } @Override public boolean writeField(Object value) throws IOException, IllegalAccessException { if (!serialized) return false; Object fieldValue = field.get(value); return fieldValue != value; // avoid recursion for example for Throwable.cause } }; } private Map getBoundFields(Gson context, TypeToken type, Class raw) { Map result = new LinkedHashMap(); if (raw.isInterface()) { return result; } Type declaredType = type.getType(); while (raw != Object.class) { Field[] fields = raw.getDeclaredFields(); for (Field field : fields) { boolean serialize = excludeField(field, true); boolean deserialize = excludeField(field, false); if (!serialize && !deserialize) { continue; } field.setAccessible(true); Type fieldType = $Gson$Types.resolve(type.getType(), raw, field.getGenericType()); List fieldNames = getFieldNames(field); BoundField previous = null; for (int i = 0, size = fieldNames.size(); i < size; ++i) { String name = fieldNames.get(i); if (i != 0) serialize = false; // only serialize the default name BoundField boundField = createBoundField(context, field, name, TypeToken.get(fieldType), serialize, deserialize); BoundField replaced = result.put(name, boundField); if (previous == null) previous = replaced; } if (previous != null) { throw new IllegalArgumentException(declaredType + " declares multiple JSON fields named " + previous.name); } } type = TypeToken.get($Gson$Types.resolve(type.getType(), raw, raw.getGenericSuperclass())); raw = type.getRawType(); } return result; } static abstract class BoundField { final String name; final boolean serialized; final boolean deserialized; protected BoundField(String name, boolean serialized, boolean deserialized) { this.name = name; this.serialized = serialized; this.deserialized = deserialized; } abstract boolean writeField(Object value) throws IOException, IllegalAccessException; abstract void write(JsonWriter writer, Object value) throws IOException, IllegalAccessException; abstract void read(JsonReader reader, Object value) throws IOException, IllegalAccessException; } public static final class Adapter extends TypeAdapter { private final ObjectConstructor constructor; private final Map boundFields; Adapter(ObjectConstructor constructor, Map boundFields) { this.constructor = constructor; this.boundFields = boundFields; } @Override public T read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } T instance = constructor.construct(); try { in.beginObject(); while (in.hasNext()) { String name = in.nextName(); BoundField field = boundFields.get(name); if (field == null || !field.deserialized) { in.skipValue(); } else { field.read(in, instance); } } } catch (IllegalStateException e) { throw new JsonSyntaxException(e); } catch (IllegalAccessException e) { throw new AssertionError(e); } in.endObject(); return instance; } @Override public void write(JsonWriter out, T value) throws IOException { if (value == null) { out.nullValue(); return; } out.beginObject(); try { for (BoundField boundField : boundFields.values()) { if (boundField.writeField(value)) { out.name(boundField.name); boundField.write(out, value); } } } catch (IllegalAccessException e) { throw new AssertionError(e); } out.endObject(); } } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/internal/bind/SqlDateTypeAdapter.java000066400000000000000000000046241316034351600324310ustar00rootroot00000000000000/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.internal.bind; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; /** * Adapter for java.sql.Date. Although this class appears stateless, it is not. * DateFormat captures its time zone and locale when it is created, which gives * this class state. DateFormat isn't thread safe either, so this class has * to synchronize its read and write methods. */ public final class SqlDateTypeAdapter extends TypeAdapter { public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() { @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal @Override public TypeAdapter create(Gson gson, TypeToken typeToken) { return typeToken.getRawType() == java.sql.Date.class ? (TypeAdapter) new SqlDateTypeAdapter() : null; } }; private final DateFormat format = new SimpleDateFormat("MMM d, yyyy"); @Override public synchronized java.sql.Date read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } try { final long utilDate = format.parse(in.nextString()).getTime(); return new java.sql.Date(utilDate); } catch (ParseException e) { throw new JsonSyntaxException(e); } } @Override public synchronized void write(JsonWriter out, java.sql.Date value) throws IOException { out.value(value == null ? null : format.format(value)); } } gson-gson-parent-2.8.2/gson/src/main/java/com/google/gson/internal/bind/TimeTypeAdapter.java000066400000000000000000000045501316034351600317700ustar00rootroot00000000000000/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.internal.bind; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.sql.Time; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Adapter for Time. Although this class appears stateless, it is not. * DateFormat captures its time zone and locale when it is created, which gives * this class state. DateFormat isn't thread safe either, so this class has * to synchronize its read and write methods. */ public final class TimeTypeAdapter extends TypeAdapter