-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Open
Labels
Description
Problem solved by the feature
Quite frequently users seem to accidentally use JSON classes from other libraries with Gson, such as JSON-java's JSONObject. This leads to incorrect results because Gson will then fall back to using reflection on these classes.
Examples:
- https://stackoverflow.com/q/6089989
- https://stackoverflow.com/q/34309811
- https://stackoverflow.com/q/42925887
- https://stackoverflow.com/q/50059808
- https://stackoverflow.com/q/66884585
- https://stackoverflow.com/q/69960938
- https://stackoverflow.com/q/71369104
- https://stackoverflow.com/q/76706456
- https://stackoverflow.com/q/76755061
- https://stackoverflow.com/q/76756548
Related:
- https://stackoverflow.com/q/32319222
- https://stackoverflow.com/q/42157126
- https://stackoverflow.com/q/56661362
Feature description
Register a default TypeAdapter (or TypeAdapterFactory) which checks if the class is from a different popular JSON library and in that case throw an exception.
- The exception should only be thrown in the
readandwritemethods ofTypeAdapterto minimize the risk of backward incompatibility when users don't actually serialize or deserialize the instances - The adapter should act as fallback (internally registered right before the reflection-based factory); a user defined adapter should have higher precedence
- The exception message mention that the class is unsupported and the Gson equivalent should be used; optionally it should also point to a new troubleshooting guide entry
Libraries with JSON classes which should be detected:
- JSON-java (these are also the ones available for Android)
- Jackson
Might not be necessary because the Jackson classes have different naming (ObjectNodefor JSON object,ArrayNodefor JSON array, though the base class is namedJsonNode), so the risk of confusion might be lower - Vert.x ?
- json-simple
Probably not necessary becauseJSONArrayextendsArrayListandJSONObjectextendsHashMap - fastjson
Probably not necessary becauseJSONArrayimplementsListandJSONObjectimplementsMap - json-smart
Probably not necessary becauseJSONArrayextendsArrayListandJSONObjectextendsHashMap - ...?
Note that this would break backward compatibility for applications which (accidentally) rely on this, but they could register a custom TypeAdapter to restore the functionality.
Alternatives / workarounds
- Do nothing
- Add default adapters which support third-party JSON classes; probably not something we want to do?