Throw exception when using classes from other JSON libraries with Gson
- Dominant language
- Java
- Stars
- 24.2k
- Forks
- 4.5k
- Avg merge
- 6d 4h
- Merged PRs (30d)
- 12
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
Relates to #673, #782
# 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 `read` and `write` methods of `TypeAdapter` to 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 (`ObjectNode` for JSON object, `ArrayNode` for JSON array, though the base class is named `JsonNode`), so the risk of confusion might be lower
- Vert.x ?
- json-simple
Probably not necessary because `JSONArray` extends `ArrayList` and `JSONObject` extends `HashMap`
- fastjson
Probably not necessary because `JSONArray` implements `List` and `JSONObject` implements `Map`
- json-smart
Probably not necessary because `JSONArray` extends `ArrayList` and `JSONObject` extends `HashMap`
- ...?
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?
Contributor guide
Assessment
This issue has not been assessed yet.